gpt4 book ai didi

gradle - 无法在Kotlin中使用扩展的类型参数编译扩展功能

转载 作者:行者123 更新时间:2023-12-03 05:01:48 24 4
gpt4 key购买 nike

我有一个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中使用扩展的类型参数编译扩展功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29765204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com