6
votes

I'm trying to convert a HashMap of elements into a JSON string. I'm using the method used in this link.

 val elementsNew: HashMap<String, Element> = HashMap(elements)
 val type = Types.newParameterizedType(Map::class.java, String::class.java, Element::class.java)
 var json: String = builder.adapter(type).toJson(elementsNew)

But this gives the following error

Error:(236, 40) Type inference failed: Not enough information to infer parameter T in fun adapter(p0: Type!): JsonAdapter! Please specify it explicitly.

Can any one tell me where's the fault? Is it because of Kotlin?

1
worth noting that it's not exactly because of Kotlin. In Java, you'd end up with JsonAdapter<Object> (wouldn't be able to use that for your Map<String, Element> type). Kotlin forces you to provide the parameterizing arguments, so you can see the mistake sooner. - Eric Cochran

1 Answers

10
votes

Looking at the signature of the adapter() method, it can't infer its type parameter from the argument:

public <T> JsonAdapter<T> adapter(Type type)

Hence you have to provide the type explicitly:

var json = builder.adapter<Map<String, Element>>(type).toJson(elementsNew)

or alternatively:

val adapter: JsonAdapter<Map<String, Element>> = builder.adapter(type)
var json = adapter.toJson(elementsNew)