简体   繁体   中英

Unable to compile an extension function with reified type parameter in Kotlin

I have a kotlin library project and use Spek for testing. In my tests I try to use the following function:

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

When I try to compile the above code, I get a compilation error:

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

However this code compiles correctly:

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

You notice, the return type was changed from T to T? . Even though it compiles, I get a hint message:

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

Is it a correct behavior?

The exception you are getting is a bug in the compiler.

The warning you are getting is correct, and to eliminate it, write <reified T: Any> , this way a plain T is not nullable any more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM