Inferring a generic type of Map in Kotlin

Viewed 6028

Consider a Java method which infers its type by Java class as follows:

public <T> T readJson(Class<T> c) throws IOException {

This allows doing something like this:

Map<String, String> map = foo.readJson(Map.class);

In java it will warn about unchecked cast, but it will work correctly. However in Kotlin, this will not be so easy, one could try using:

foo.readJson(Map::class.java)

However if Map<String, String> will be required, it will not work:

Type inference failed. Expected type mismatch.
required Map<String, String>
found Map<*, *>!

I also tried defining an interface StringMap:

interface StringMap : Map<String, String>

However that does not work either, it will lead to exceptions like this:

Cannot cast ...LinkedTreeMap to ...StringMap

What would be a correct way of doing this?

1 Answers
Related