如何将函数传递给 Kotlin 中的函数
How to pass functions to function in Kotlin
我想将一个或多个函数传递给一个函数,但只要它是函数文字或包函数,它就可以工作,但是当我将它更改为特定 class 的函数时(成员函数)我有以下问题
假设我有这两个功能
fun foo() { //doSomething }
fun bar(function: () -> Unit) {
//anotherThing!
function()
}
当我打电话给
bar(foo())
或
bar(::foo)
我遇到了类型不匹配的问题
(必填: ()->Unit , 找到: Unit)
注:不想这样解决
bar( { foo() } )
或
bar {
foo()
}
我刚刚检查了你的例子。这对我有用。 Kotlin 版本 1.0.0-beta-2423
在 Kotlin 1.1 及更高版本中,您可以使用 bound callable references。例如bar(::foo)
.
在second 1.0 Beta Candidate and other prior versions you could not pass around member functions. This issue was tracked as KT-6947.
我想将一个或多个函数传递给一个函数,但只要它是函数文字或包函数,它就可以工作,但是当我将它更改为特定 class 的函数时(成员函数)我有以下问题
假设我有这两个功能
fun foo() { //doSomething }
fun bar(function: () -> Unit) {
//anotherThing!
function()
}
当我打电话给
bar(foo())
或
bar(::foo)
我遇到了类型不匹配的问题 (必填: ()->Unit , 找到: Unit)
注:不想这样解决
bar( { foo() } )
或
bar {
foo()
}
我刚刚检查了你的例子。这对我有用。 Kotlin 版本 1.0.0-beta-2423
在 Kotlin 1.1 及更高版本中,您可以使用 bound callable references。例如bar(::foo)
.
在second 1.0 Beta Candidate and other prior versions you could not pass around member functions. This issue was tracked as KT-6947.