【问题标题】:Using Java Void type in Kotlin在 Kotlin 中使用 Java Void 类型
【发布时间】:2015-11-19 15:31:56
【问题描述】:

由于类型限制,我有一个 Java 函数需要我传递 Void 参数。比如:

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

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

foo(null);

我必须向该函数传递什么以便 Kotlin 编译器接受它?

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

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

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

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

【问题讨论】:

  • 您是否尝试过将变量设置为空?该函数使用的是 INT 还是 OBJECT?如果是这样,可以在尝试访问或更改它之前将其设置为 NULL。这是您正在调用的方法还是从另一个类继承的?
  • 实际上我继承了一个应该返回Map&lt;String, Void&gt;并希望返回return mapOf(Pair("foo", null))的函数
  • 编译器给出的确切错误信息是什么?我无法在孤立的样本中重现该问题,即您应该能够将 null 传递给 Void 参数
  • @AlexanderUdalov Error:(33, 16) Kotlin: Type inference failed. Expected type mismatch: inferred type is kotlin.Map&lt;kotlin.String, kotlin.Nothing?&gt; but kotlin.Map&lt;kotlin.String, java.lang.Void&gt; was expected。这是 Kotlin 的 Beta 2 版本。
  • 您是否尝试将其更改为Void?

标签: java kotlin


【解决方案1】:

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

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

解释:Map&lt;String, Void&gt; 期望没有 null 值。但是您正在创建一个具有null 值的Pair。人们建议使用null 调用需要Void 的java 方法,据我所知,这应该可以工作,但是对于您正在使用的Pair 构造函数,您肯定需要明确声明Map 可以包含空值。

编辑:我对 necro-ing 不好,直到之后才考虑日期。 :(

【讨论】:

  • 这应该是公认的答案。如果要传递 null,请务必使用可为 null 的类型。
  • 这是我认为 kotlins 应该处理的一种特殊情况。 void 类型将始终为 null
【解决方案2】:

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

【讨论】:

  • 我的插件实际上是最新的:1.0.0-beta-2423-IJ143-13 但问题仍然存在
  • 我的插件版本和 aga (1.0.0-beta-1103-IJ143-27) 一样。我正在使用IntelliJ IDEA Community Edition 15.0.1,aga 发布的代码在我的环境中有效。
【解决方案3】:

我想出了 2 个解决方案,它们都可以编译(在 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?))
}

祝你好运。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多