【问题标题】:Unable to compile an extension function with reified type parameter in Kotlin无法在 Kotlin 中编译具有具体类型参数的扩展函数
【发布时间】:2015-06-28 04:49:08
【问题描述】:

我有一个 kotlin 库项目并使用 Spek 进行测试。在我的测试中,我尝试使用以下功能:

inline fun JsonElement?.cast<reified T>(gson: Gson): T {
  return if (this != null)
    gson.fromJson<T>(this, javaClass<T>())
  else null
}

当我尝试编译上面的代码时,我得到一个编译错误:

Error: Gradle: java.lang.IllegalStateException: Error type encountered:
org.jetbrains.kotlin.types.ErrorUtils$UninferredParameterTypeConstructor@144bac7f (ErrorTypeImpl).
One of the possible reasons may be that this type is not directly accessible from this module.
To workaround this error, try adding an explicit dependency on the module
or library which contains this type to the classpath

但是,这段代码可以正确编译:

inline fun JsonElement?.cast<reified T>(gson: Gson): T? {
  return if (this != null)
    gson.fromJson<T>(this, javaClass<T>())
  else null
}

您注意到,返回类型已从 T 更改为 T?。即使它编译了,我也会收到一条提示消息:

'T' has nullable upper bound. This means that a value of type may be null.
Using 'T?' is likely to mislead the reader.

这是正确的行为吗?

【问题讨论】:

  • 我不想误导读者,那我应该写什么呢?
  • &lt;reified T: Any&gt;,这样一个普通的T就不能再为空了
  • 为了使其更正确并包含通用类型信息,您还需要更改为使用 Gson TypeToken。请参阅stackoverflow.com/a/33420043/3679676 以获得这样做的答案。
  • gradle 标签应该被移除,这与 Gradle 无关,并且在当时任何使用 Kotlin 编译器时都会出现。

标签: gradle kotlin


【解决方案1】:

您遇到的异常是编译器中的错误。

你得到的警告是正确的,为了消除它,写&lt;reified T: Any&gt;,这样一个普通的T就不能再为空了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2018-02-19
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 2021-03-22
相关资源
最近更新 更多