首页 文章

在Kotlin中使用Java Void类型

提问于
浏览
10

我有一个Java函数,由于类型约束,我需要传递 Void 参数 . 就像是:

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

现在我想从Kotlin调用该函数,但编译器抱怨当我用 null 调用它时类型是不兼容的,就像我从Java那样:

foo(null);

我必须传递给该函数以便Kotlin编译器接受它吗?

Update: 实际代码如下所示:

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

Update: 使用 null as Void 实际上也不起作用:

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

3 回答

  • 6

    没有机会尝试它,但纯粹基于您的异常,以下代码应该工作:

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

    说明: Map<String, Void> 期望没有 null 值 . 但是你创建的 Pair 值为 null . 人们建议调用需要 Voidnull 的java方法,据我所知,这应该可以工作,但对于你正在使用的 Pair 构造函数,你肯定需要明确声明 Map 可以包含空值 .

    Edit: 我对坏死的不好,没想到之后的日期 . :(

  • 0

    尝试更新您的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)
    }
    
  • 3

    我想出了两个解决方案,两个都编译(在Kotlin 1.1.2-3下) .

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

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

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

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

    祝好运 .

相关问题