Kotlin中的通用lambda或函数值types
给定一个函数
fun to5(x: T): Int = 5
有没有可能像这样将其赋值给variables(值) funVal
?
val funVal: (T) -> Int = ::to5
无
未解决的参考:T
错误?
换句话说,有可能以某种方式告诉Kotlin funVal
types声明中的T
是一个types参数?
比如像这样:
val funVal: (T) -> Int = ::to5 val funVal: (T) -> Int = ::to5 val funVal: (T) -> Int = ::to5 val funVal: ((T) -> Int) = ::to5
用例
我的用例是使用generics的咖喱。 概念:
fun pairStrWithStr(s: String): (String) -> Pair = { Pair(s, it) } val pairStrWithAbc: (String) -> Pair = pairStrWithStr("abc") pairStrWithAbc("xyz") // (abc, xyz)
制作第二个参数通用:
fun pairStrWithAny(s: String): (T) -> Pair = { Pair(s, it) } // Compilation ERROR: Unresolved reference: T val pairAnyWithAbc: (T) -> Pair = pairStrWithAny("abc")
当然,我可以提供Any
types的:
val pairAnyWithAbc: (Any) -> Pair = pairStrWithAny("abc")
但是,然后我失去了types信息:
pairAnyWithAbc(5) // Pair
我能想到的解决方案是:
包装在通用的乐趣 (基本上不是真正的咖啡或高阶function的使用)
fun pairAnyWithAbc(t: T) { return pairAnyWithAbc(t) }
为每种types创建函数 (不需要使用generics)
val pairStrWithAbc: (String) -> Pair = pairStrWithAny("abc") val pairIntWithAbc: (Int) -> Pair = pairStrWithAny("abc")
只有类和函数可以在Kotlin中具有genericstypes参数。 如果你确实需要一个属性来获得一个genericstypes,那么它必须属于一个可以提供genericstypes的类实例,如下所示:
class Foo { val funVal: (T) -> Int = ::to5 }
这里有更多的讨论,我只是不能把这个标记为重复的,因为这个问题没有被接受的答案。