成员函数不能用作参数
用下面的代码:
fun someFun(x: Any) { } fun foo(bar: (val x: Any) -> Unit) { } fun baz() { foo(::someFun) } class Test { fun someFun(x: Any) { } fun foo(bar: (val x: Any) -> Unit) { } fun baz() { foo(::someFun) } }
在类之外的代码中,一切正常,没有错误。 在Test :: baz中调用foo
,出现以下错误:
错误:(53,13)Kotlin:类型不匹配:推断的类型是kotlin.reflect.KMemberFunction1,但是(kotlin.Any) – > kotlin.Unit是预期的
为什么我不能使用成员函数作为这样的参数? 该文件并没有说我不能这样做。
文档
如果我们需要使用类的成员或扩展函数,那么它需要被限定,结果将是类型“扩展函数”,例如String :: toCharArray给了我们一个类型为String:String的扩展函数。 () – > CharArray。
foo(Test::someFun)
类型更改为:
bar: Test.(Any) -> Unit
你也可以传递一个lambda函数来解决这个问题:
foo { bar -> someFun(bar) }
在Test类中
更改代码
fun baz() { foo(::someFun) }
至
fun baz() { foo(this::someFun) }
会解决问题!
如果你想引用一种功能,比方说
(Int,Int)->String
你有A班
class A{ fun whatever(a:Int,b:Int) = "${a},${b}" }
你可以使用A()::whatever
来引用函数,其中A()表示A的一个实例