在Kotlin中使用Java Voidtypes

我有一个Java函数,需要我通过一个Void参数由于types约束。 就像是:

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

现在我想从Kotlin中调用这个函数,但是编译器会抱怨,当我像从Java那样用null调用它时,types是不兼容的:

 foo(null); 

我有什么要传递给该函数,以便Kotlin编译器接受它?

更新:实际的代码如下所示:

 fun foo(): Map { return mapOf(Pair("foo", null)) } 

更新:使用null as Void实际上也不工作:

 kotlin.TypeCastException: null cannot be cast to non-null type java.lang.Void 

没有机会尝试它,但纯粹基于你的例外,下面的代码应该工作:

 fun foo(): Map { return mapOf(Pair("foo", null)) } 

说明: Map期望没有null值。 但是你正在创建一个null值的Pair 。 人们建议调用需要Void的java方法,这个方法应该尽我所能,但对于你使用的Pair构造函数,你肯定需要明确声明Map可以包含空值。

编辑:我的坏坏,没有想到之前的日期。 🙁

尝试更新您的Kotlin插件。 我在’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) } 

我提出了两个解决方案,他们都编译(根据Kotlin 1.1.2-3)。

您可能需要(不改变您的方法签名,但它不起作用):

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

或类似的东西(改变你的签名,它的作品):

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

祝你好运。