简体   繁体   English

在Kotlin中使用Java Void类型

[英]Using Java Void type in Kotlin

I have a Java function that requires me to pass a Void parameter due to type constraints. 我有一个Java函数,由于类型约束,我需要传递一个Void参数。 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: 现在我想从Kotlin调用该函数,但编译器抱怨当我用null调用它时类型是不兼容的,就像我从Java那样:

foo(null);

What do I have to pass to that function so that the Kotlin compiler accepts it? 我必须传递给该函数,以便Kotlin编译器接受它?

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: 更新:使用null as Void实际上也不起作用:

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. 说明: Map<String, Void>期望不存在null值。 But you're creating a Pair with a null value. 但是你要创建一个具有null值的Pair 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. 人们建议调用需要Void with null的java方法,据我所知,这应该可以工作,但对于你正在使用的Pair构造函数,你肯定需要明确声明Map可以包含空值。

Edit: my bad for necro-ing, didn't think about the date until after. 编辑:我对坏死的不好,没想到之后的日期。 :( :(

Try to update your Kotlin plugin. 尝试更新您的Kotlin插件。 I'm on '1.0.0-beta-1103-IJ143-27' and the following code compiles without any complaints/warnings: 我在'1.0.0-beta-1103-IJ143-27'并且以下代码编译时没有任何投诉/警告:

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

    }
}

// On Kotlin side
fun testVoid() {
    Test().test(null)
}

I had came up with 2 solutions, both of them compiles (under Kotlin 1.1.2-3). 我想出了两个解决方案,两个都编译(在Kotlin 1.1.2-3下)。

You might need this (not changing your method signature but it doesn't work): 您可能需要这个(不更改您的方法签名,但它不起作用):

fun foo(): Map<String, Void> {
  return mapOf(Pair("foo", throw Exception("Why? Why you call me")))
}

Or something like (changing your signature and it works): 或类似的东西(改变你的签名,它的工作原理):

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

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM