Home » Android » android – Java / Kotlin equivalent of Swift [String : [String : Any]]

android – Java / Kotlin equivalent of Swift [String : [String : Any]]

Posted by: admin June 15, 2020 Leave a comment

Questions:

What is the equivalent of [String : [String : Any]] from Swift in Kotlin or Java language?

I need to retrieve from database a structure that looks like this:

Key:
    Key : Value
    Key : Value
    Key : Value
Key :
    Key : Value
    Key : Value
    Key : Value
How to&Answers:

This structure can be represented by a Map<String, Map<String, Any>>. The Kotlin code for creating such a type:

val fromDb: Map<String, Map<String, Any>> = mapOf(
    "Key1" to mapOf("KeyA" to "Value", "KeyB" to "Value"),
    "Key2" to mapOf("KeyC" to "Value", "KeyD" to "Value")
)

In Java, as of JDK 9, it can be expressed like this:

Map<String, Map<String, Object>> fromDb = Map.of(
    "Key1", Map.of("KeyA", "Value", "KeyB", "Value"),
    "Key2", Map.of("KeyC", "Value", "KeyD", "Value")
);

Note that the Any type in Kotlin is basically the same as Object in Java.