0

I'm curious to know if Kotlin has the same/kind of support for explicit maps of maps (like javascript objects). Swift already supports this as well as Dart, I think. I know Java doesn't so that might be a reason as to why Kotlin might not have it.

Here you can see how it's done in Swift. Can i do something similar with kotlin?

print([
    "1": "lel",
    "2": [
        "2": 2
    ],
])
2
  • what is that you want to achieve? just not having to assign to a variable for logging? Commented Dec 19, 2019 at 18:06
  • I want to have the same data structure as the above in kotlin explicitly Commented Dec 19, 2019 at 18:09

2 Answers 2

1

Not exactly, its static so it still needs to interoperate.

They do have a dynamic type though which works around it..

Kotlin dynamic

Expressions using values of dynamic type are translated to JavaScript "as is", and do not use the Kotlin operator conventions.

Sign up to request clarification or add additional context in comments.

Comments

1

To answer your question, no, not really. Kotlin is statically typed, so if you want a map to contain keys of multiple types, you'd be creating a Map<String, Any>. That's not necessarily the worst thing, if you just want to print it. Kotlin also has a nice inline to function for constructing values within a map:

fun main() {
    val v = mapOf(
        "1" to "lel",
        "2" to mapOf("2" to 2)
    )
    println(v)
}

prints:

{1=lel, 2={2=2}}

Any other probing into the values that exist within the map, you'd have to be manually checking the type.

Edit: Object Expressions are also a thing, but still probably aren't what you're looking for

Anonymous objects aren't the same thing as maps of maps. They have to have valid identifiers and cannot be dynamically added to like in JavaScript, (e.g. foo['prop'] = 5 works for any object foo in JavaScript). They also come with caveats:

Note that anonymous objects can be used as types only in local and private declarations. If you use an anonymous object as a return type of a public function or the type of a public property, the actual type of that function or property will be the declared supertype of the anonymous object, or Any if you didn't declare any supertype. Members added in the anonymous object will not be accessible.

Their main use is to create anonymous implementations of supertypes or interfaces. If you want to be returning this and passing it around, I'd stick with maps of maps, or create a data class. Idiomatic Kotlin takes advantage of the fact that classes are really cheap and can be done in one line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.