可以引用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)
}

Kotlin相关问答推荐

数据源配置

如何创建一个空的kotlin工作?

如何在 kotlin 中的数据类中为变量提供多种类型

在Kotlin lambda的参数中如何指定函数类型?

如何在数据类中删除空格 (String)?

Kotlin 可空泛型

Jetpack Compose:当状态从另一个活动改变时强制重组

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

类型是什么意

如何创建 Kotlin DSL - DSL 语法 Kotlin

将 Gradle 子元素与 Kotlin 多平台一起使用

Gradle 同步失败:不支持的方法:KotlinPlatformContainer.supports()

Kotlin - 覆盖方法中的 IllegalArgumentException

如何在使用 Gradle 的 AppEngine 项目中使用 Kotlin

Android Studio 将 Java 转换为 Kotlin 错误无法推断此参数的类型

Kotlin:使用Gradle进行增量编译

Kotlin替换字符串中的多个单词

Kotlin内联属性的用例是什么?

在 Kotlin 中编写一个等于 Int.MIN_VALUE 的十六进制整数文字

java.lang.NoClassDefFoundError:解析失败:Lkotlin/time/MonoClock