类型不匹配推断的类型是单位,但Void是预期的

带有字符串和侦听器的kotlin方法(类似于swift中的闭包)参数。

fun testA(str: String, listner: (lstr: String) -> Void) { } 

像这样调用它。

 testA("hello") { lstr -> print(lstr) } 

错误:类型不匹配推断的类型是单位,但预期Void

什么是单位? 封闭的返回类型是Void 。 阅读很多其他问题,但可以用这个简单的方法找到这里发生了什么。

根据Kotlin文档,单元类型对应于Java中的void类型。 所以在Kotlin中没有返回值的正确函数是

 fun hello(name: String): Unit { println("Hello $name"); } 

或者什么也不用

 fun hello(name: String) { println("Hello $name"); } 

Kotlin使用Unit来返回Nothing而不是Void 。 它应该工作

 fun testA(str: String, listner: (lstr: String) -> Unit) { } 

如果你确实需要Void (这很少有用,但可能是在与Java代码互操作的时候),所以你需要返回null因为Void被定义为没有实例(与Scala / Kotlin Unit完全相反):

 fun testA(str: String, listner: java.util.function.Function<String, Void?>) { ... } testA(("hello") { lstr -> print(lstr) null }