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
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. :(
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)
}
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