Reputation: 3076
Is it possible to make reference to generic functions in 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>
Upvotes: 22
Views: 2632
Reputation: 1559
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
Or you can use typealias
to do a work around, if you are using function as arguments:
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)
}
Upvotes: 9