11
votes

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.

3

3 Answers

4
votes

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")
}

The

6
votes

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
}
2
votes

Kotlin uses Unit for methods which return nothing instead of Void. It should work

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

}