A kotlin method with a string and a listener (similar to closure in swift) parameters.
fun testA(str: String, listner: (lstr: String) -> Void) {
}
Calling it like this this.
testA("hello") { lstr ->
print(lstr)
}
Error: Type mismatch inferred type is Unit but Void was expected
What's Unit?? Return type of the closure is Void
. Read lot of other questions but could find what's going on here with this simple method.
According to Kotlin documentation Unit type corresponds to the void type in Java. So the correct function without returning value in Kotlin is
fun hello(name: String): Unit {
println("Hello $name")
}
Or use nothing
fun hello(name: String) {
println("Hello $name")
}
If you do need Void
(it's rarely useful, but could be when interoperating with Java code), you need to return null
because Void
is defined to have no instances (in contrast to Scala/Kotlin Unit
, which has exactly one):
fun testA(str: String, listner: java.util.function.Function<String, Void?>) {
...
}
testA(("hello") { lstr ->
print(lstr)
null
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With