6

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?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Sanka Darshana
  • 1,391
  • 1
  • 23
  • 41
  • 1
    worth noting that it's not exactly because of Kotlin. In Java, you'd end up with `JsonAdapter` (wouldn't be able to use that for your `Map` type). Kotlin forces you to provide the parameterizing arguments, so you can see the mistake sooner. – Eric Cochran Dec 15 '17 at 22:09

1 Answers1

11

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)
Egor
  • 39,695
  • 10
  • 113
  • 130