Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch inferred type is Unit but Void was expected

Tags:

kotlin

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.

like image 345
Bilal Avatar asked Oct 26 '17 03:10

Bilal


2 Answers

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")
}
like image 177
vishal jangid Avatar answered Sep 22 '22 05:09

vishal jangid


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
}
like image 29
Alexey Romanov Avatar answered Sep 19 '22 05:09

Alexey Romanov