The mismatch type of the alleged type is Unit, but Void was expected

The kotlin method with a string and a listener parameter (similar to closing in fast).

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

}

A call of this type.

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

Error: The type of invalid mismatch type is Unit, but Void is expected to be

Which unit? Return return type Void. Read a lot of other questions, but you can find out what's happening here with this simple method.

+4
source share
3 answers

According to the Kotlin documentation, the element type corresponds to the void type in Java. So the correct function without return value in Kotlin

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

Or do not use anything

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

+2
source

Kotlin Unit , Void.

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

}
+1

If you really need to Void(this is rarely useful, but can be when interacting with Java code), you need to return nullbecause it Voidhas no instances (unlike Scala / Kotlin Unit, which has exactly one):

fun testA(str: String, listner: java.util.function.Function<String, Void?>) {
...
}

testA(("hello") { lstr ->
    print(lstr)
    null
}
+1
source

Source: https://habr.com/ru/post/1688194/


All Articles