1

Hi i'am new to Kotlin and i would like to do an array with named parameter. In Swift i can do :

let analytics = ["organization_login": "toto", "organization_name": "titi", "lead_email": "tata"]

The type is : [String: String]

I Looked all Array and Arraylist in kotlin but i couln't find the equivalent.

What i want it's to be able to give parameter name for my array.

Edit

I misunderstood the swift syntaxe, it's seem that it's only a dictonary, so we just have to use map.

2
  • 1
    I'm not too sure about this swift construct, but it really looks like a Map<String, String> Commented Feb 21, 2020 at 14:11
  • 1
    Even in Swift, this isn't an array. It's a Dictionary. Commented Feb 21, 2020 at 14:13

2 Answers 2

3

The reason is that [String: String] is not an array, it's a Dictionary.

The equivalent of Dictionary in Kotlin is Map.

Maps can be created like so:

val map = mapOf("string_one" to "string_2", "string_3" to "string_4")

or, if you want to mutate it:

val mutableMap = mutableMapOf("string_one" to "string_2")
Sign up to request clarification or add additional context in comments.

1 Comment

Also worth pointing out: unlike an Array, a Map is unordered. So if you need the mappings to be in a particular order, you should either use a particular implementation (such as LinkedHashMap) that preserves iteration order, or use something else. (Similarly, you can't have multiple mappings for the same key; that's a multi-map.) Finally, you can't access mappings by index; instead, you look up the value for a particular key, e.g. map["string_one"] (or, equivalently, map.get("string_one")) which returns "string_2".
2

You need to use Map as

val map = mapOf("organization_login" to "toto", "organization_name" to "titi") 
// immutable map

you can also use sortedMapOf, hashMapOf linkedMapOf etc for different algo based storage.

Note: If you want to add more elements later then make sure to use mutableMapOf

2 Comments

Thanks it's what i wanted
I am glad that I could help, Happy coding!

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.