0

Presently if I have to define a nested/hierarchal Map something like Map<String, Map<String, Map<String, String>>>, I have to separately define each nested map separately and use them to manually build the hierarchy. Is there a simpler way to declare and define such maps? Something similar to what I can do in Javascript.

PS: new to Kotlin

Javascript example (Hypothetical Example).

var schema = {
    "US": {
        "WA": {
            "Seattle": "Pike Street"
        }
    },
    "IN" : {
        "Karnataka": {
            "Bangalore" : "MG Road"
        }
    }
};

Kotlin:

val WA_CITY_TO_ST_MAP = mapOf(
    "Seattle" to "",
    "Redmond" to "1st Ave"
)
val KARNATAKA_CITY_TO_ST_MAP = mapOf("Bangalore" to "MG Road")

val US_STATE_TO_CITIES_MAP = mapOf("WA" to WA_CITY_TO_ST_MAP)
val IN_STATES_TO_CITIES_MAP = mapOf("Karnataka" to KARNATAKA_CITY_TO_ST_MAP)

val schema = mapOf("US" to US_STATE_TO_CITIES_MAP, "IN" to IN_STATES_TO_CITIES_MAP)

Keen Sage
  • 1,899
  • 5
  • 26
  • 44
  • Any example how you define it in Javascript? – Animesh Sahu Jul 26 '20 at 15:05
  • Added what I trying to achieve. I am also not sure why kotlin chose to have "to" keyword when ":" could have done the same job. – Keen Sage Jul 26 '20 at 19:34
  • 1
    [`to`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to.html) is not a keyword, not part of the language; it's just an ordinary extension function defined in the standard library.  (You couldn't call a function `:`, so that _would_ need to be defined in the language itself.) – gidds Jul 26 '20 at 20:59
  • 1
    The language design avoids using symbols across different domains. `:` is already used for the domain of type. Part of the reason they haven’t added the ternary operator is that `?` has to do with nullability any time you see it in Kotlin and the ternary operator would break that rule. – Tenfour04 Jul 26 '20 at 21:15

1 Answers1

1

The nested maps can be built inline, there's no need to initialise them as separate vals:

val schema = mapOf(
            "US" to mapOf(
                    "WA" to mapOf(
                            "Seattle" to "",
                            "Redmond" to "1st Ave"
                    )
            ),
            "IN" to mapOf(
                    "Karnataka" to mapOf(
                            "Bangalore" to "MG Road"
                    )
            )
    )

If your structure doesn't always have the same level of nesting (much like JSON), you might want to look at handling your data with an appropriate JSON library.

KurtMica
  • 992
  • 7
  • 16