javakotlinkotlin-java-interop

Java Types in Kotlin


I am working with a Java Lib in Kotlin. One (important) function needs a java.util.HashMap <String, Object> as parameter.

In Java most Types are a part of java.lang.Object. Not so in Kotlin, they are part of Any.

I need to put in the HashMap a String Key and Values from type String and int. Like this:

val parameters = java.util.HashMap<String,Object>()
parameters.put("Key1", 5)
paramerers.put("Key2", "Hello")

Of course, they are Kotlin Types in this case which do not extend the Java Object class. My problem is they have to be part of java.lang.Object in order to use the lib. How can I archive this?

Thank you in advance.


Solution

  • Any and Object are mapped types. Java code sees every class as a descendent of Object (whether or not it was defined in Kotlin), and Kotlin sees every class as a descendent of Any (whether or not it was defined in Java). When you pass objects from Kotlin to a Java class, they satisfy the Object type requirement.

    Kotlin can also refer to the Object type, but it's cleaner not to, or it causes issues like what you ran into. You can use Any to represent the same thing. The Java method that takes it as an argument won't complain. You also don't need to specify java.util.HashMap because the Kotlin HashMap and Java HashMap are the same class. The Kotlin version is just a typealias of the Java HashMap.

    Your code above is equivalent to:

    val parameters = HashMap<String, Any>()
    parameters.put("key1", 5)
    parameters.put("key2", "Hello")
    

    or the more typical Kotlin pattern of:

    val parameters = hashMapOf<String, Any>(
        "key1" to 5,
        "key2" to "Hello"
    )