Krzysztof Palka Krzysztof Palka - 3 months ago 25
Java Question

Kotlin map & reduce array of Strings to Map<String, Any!>

I want to create Kotlin utility accessible from Java that converts list of Strings to Map. So far I've written:

class Utils {
companion object {
@JvmStatic fun values(item: GSAItem): Map<String, Object> {
return item.itemDescriptor.propertyNames.map {it -> Map.Entry<String, Any!>(it, item.getPropertyValue(it)) }; }
}
}


But I'm getting error

Error:(16, 74) Kotlin: Unresolved reference: Entry


GSAItem.getPropertyValue is Java method which takes String as argument and returns Object. After that I suspect I need to find some equivalent of collect function from Java 8?

Answer

Map.Entry - stdlib - Kotlin Programming Language is an interface and as such it does not have a constructor which is why you are getting an error (perhaps not the best message). You can find an implementation, make your own, or use associate instead:

class Utils {
    companion object {
        @JvmStatic fun values(item: GSAItem): Map<String, Any?> {
            return item.itemDescriptor.propertyNames.associate { it to item.getPropertyValue(it) }
        }
    }
}

Note that you should use Any or Any? instead of java.lang.Object.

Comments