Consider a Java method which infers its type by Java class as follows:
public T readJson(Class c) throws IOException {
This
Kotlin does not have anything like Java raw types (which were left in Java for backward compatibility), and the type system therefore does not allow this kind of unchecked assignment to be made implicitly (star projections, the closest concept to raw types in Kotlin, retain type safety).
You can make an unchecked cast to Map
, thus expressing that you are aware of a possible type mismatch at runtime:
@Suppress("UNCHECKED_CAST")
val result = foo.readJson(Map::class.java) as Map
You can suppress the unchecked cast warning for a broader scope than just one statement.
A natural improvement of this solution is writing a util function to hide the unchecked cast in it:
@Suppress("UNCHECKED_CAST")
inline fun JsonReader.readJson(): T {
val result = readJson(T::class.java)
return result as T
}
This solution uses an inline function with a reified type parameter: the function is transformed and substituted at each of its call sites, with T
replaced by the specified (or inferred) type at compile time .
Usage examples:
val map = jsonReader.readJson
fun processMap(map: Map is inferred for this call