无法在Kotlin中使用reified类型参数编译扩展函数

时间:2015-04-21 07:06:19

标签: gradle kotlin

我有一个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.

这是正确的行为吗?

1 个答案:

答案 0 :(得分:1)

您获得的异常是编译器中的错误。

您收到的警告是正确的,要消除它,请写<reified T: Any>,这样普通的T就不再可以为空了。