在 Kotlin 中,我可以將函式分配給val
.
fun intListCat(a: List<Int>, b: List<Int>): List<Int> = a.plus(b)
fun testIntListCat() {
val f = ::intListCat
println( f( listOf(1,2), listOf(30,40) ) )
}
但是當我使函式通用時,我無法將它分配給val
.
fun<T> listCat(a: List<T>, b: List<T>): List<T> = a.plus(b)
fun testListCat() {
// error: Not enough information to infer type variable T.
val f1 = ::listCat
println( f1( listOf(1,2), listOf(30,40) ) )
// error: Unresolved reference T.
val f2: (List<T>, List<T>) -> List<T> = ::listCat
println( f2( listOf(1,2), listOf(30,40) ) )
}
令我驚訝的是,對一個簡單函式的微小更改似乎使其失去了在 Kotlin 中作為高階函式的資格,該函式旨在盡可能地發揮功能。
兩年多前,在 Kotlin 社區支持頁面上有一個類似的問題。社區無法明確回答。Kotlin 團隊沒有回應。
我只是想知道從那時起 Kotlin 或程式員知識是否發生了任何變化,以允許val
在 2022 年將通用函式分配給 a?
我在 macOS 11.3.1 上運行 Kotlin 1.6.20 和 Java 17.0.2。
uj5u.com熱心網友回復:
不,這是不可能的。為了val f1 = ::listCat
按照您想要的方式作業,f1
也需要是通用的,但本地屬性不能是通用的。
通過顯式指定型別并T
用實際型別替換,您可以分配::listCats
給本地屬性:
val f: (List<Int>, List<Int>) -> List<Int> = ::listCat
盡管現在您不能將其他型別的串列傳遞給f
,這可能是不可取的。
另一方面,非本地屬性可以是泛型的,但它們的型別引數必須在接收器引數中使用,這意味著該屬性必須是擴展屬性,所以這可能對您沒有幫助試圖做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470401.html
上一篇:基于函式引數值的窄物件鍵
下一篇:動態分配不規則矩陣