Java constructor specificity


I’m trying to understand how Kotlin selects which java constructor to call based on the arguments passed.

I’m trying to call org.json.JSONObject(java.util.Map map) constructor from kotlin, but fail to do so. Everything I try and pass the constructor ends-up calling the JSONObject(java.lang.Object bean)

For example, I would expect the following sample code to call the map constructor, but it does not :

val javaMap = java.util.HashMap<String, Object>()
javaMap.put("hello", "world" as java.lang.Object)
val jsonObject = JSONObject(javaMap as Map<String, Object>)

Is this the expected behavior ? What way would I have to explicitly call the map constructor (other than reflection) ?

I’ve put up a small git repos with a test that demonstrate my issue :

Thanks in advance.

Indeed, it's a little bit confusing.

I’m not sure about all the details that causing it, but just removing “import java.util.Map” and thus using kotlin.Map instead will make your test pass.
Instead of Object please use Any, and then you don’t need any casts here, so this is how it works:

package demo 

import org.json.JSONObject
import kotlin.test.assertEquals
import org.junit.Test as test

class TestJavaConstructor {
  test fun f() {
  val javaMap = java.util.HashMap<String, Any>()
  javaMap.put(“hello”, “world”)
  val jsonObject = JSONObject(javaMap)
  assertEquals(“{hello:world}”, jsonObject.toString())

Thanks, it works great this way.