无法使用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.
这是一个正确的行为?
你得到的异常是编译器中的一个错误。
你所得到的警告是正确的,为了消除它,写出<reified T: Any>
,这样一个普通的T
不能再空。
- 制作模块化Gradle项目的最佳方法
- 如何将Kotlin代码编译为JavaScript以供我的LibGDX Web应用程序使用?
- Kotlin Back-Tick在方法名称中转义:它是如何工作的?
- Android测试失败时,Gradle构建失败,“字符串索引超出范围”
- 将Kotlin下载到Android Studio时出现与证书相关的错误
- 从gradle运行HelloAndroid?
- 如何添加kotlin类到gradle JavaCompile任务
- Kotlin插件错误:无法为类org.jetbrains.kotlin.gradle.tasks.KotlinCompile生成代理类
- 构建包含混合Groovy,Kotlin的IntelliJ项目的jar时出错