Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java Void type in Kotlin

Tags:

java

kotlin

I have a Java function that requires me to pass a Void parameter due to type constraints. Something like:

void foo(Void v) {
    // do something
}

Now I would like to call that function from Kotlin, but the compiler complains that the types are not compatible when I call it with null like I would from Java:

foo(null);

What do I have to pass to that function so that the Kotlin compiler accepts it?

Update: the actual code looks like this:

fun foo(): Map<String, Void> {
    return mapOf(Pair("foo", null))
}

Update: using null as Void actually doesn't work either:

kotlin.TypeCastException: null cannot be cast to non-null type java.lang.Void
like image 322
TBieniek Avatar asked Nov 19 '15 15:11

TBieniek


2 Answers

Haven't had a chance to try it, but based purely on your exception the following code should work:

fun foo(): Map<String, Void?> {
    return mapOf(Pair("foo", null))
}

Explanation: Map<String, Void> is expecting there to be no null values. But you're creating a Pair with a null value. People are suggesting invoking the java method requiring Void with null which should work as far as I'm aware, but for the Pair constructor you're using you definitely need to explicitly state that the Map can contain null values.

Edit: my bad for necro-ing, didn't think about the date until after. :(

like image 122
Connor Spencer Harries Avatar answered Sep 19 '22 00:09

Connor Spencer Harries


Try to update your Kotlin plugin. I'm on '1.0.0-beta-1103-IJ143-27' and the following code compiles without any complaints/warnings:

// On Java side
public class Test {
    public void test(Void v) {

    }
}

// On Kotlin side
fun testVoid() {
    Test().test(null)
}
like image 21
aga Avatar answered Sep 20 '22 00:09

aga