可以引用Kotlin中的泛型函数吗?
For example, let's say I have a function:
fun inline <reified T> appendToString(a: T, b: T) = a.toString() + b.toString
How can you reference this function? This will not compile
var a = ::appendToString<Int>
可以引用Kotlin中的泛型函数吗?
For example, let's say I have a function:
fun inline <reified T> appendToString(a: T, b: T) = a.toString() + b.toString
How can you reference this function? This will not compile
var a = ::appendToString<Int>
Essentially you have to define the property type and then put generic functions in it. Like Max mentioned it in the question's comment section.
// generic function
fun <T> appendToString(a: T, b: T) = a.toString() + b.toString()
// Failed, since cannot type inference
val temp = ::appendToString
// Failed, invalid syntax, since you cannot use type parameters this way
val temp2 = ::appendToString<String, String>
// Success, valid syntax to define type, unlike previous temp2 example, and resolved the type inference issue in temp1, since you spelled it out for the compiler
val temp3: (String, String) -> String = ::appendToString
或者,如果使用函数作为参数,可以使用typealias
进行变通:
typealias TypedAppendToString = (String, String) -> String
fun <T> appendToString(a: T, b: T) = a.toString() + b.toString()
fun refToFunction(appendToString: TypedAppendToString) {
appendToString.invoke("daf", "daf")
}
fun main() {
refToFunction(::appendToString)
}