Weird behavior when set Array of Strings to HashMap in Kotlin

I'm tryna add to HashMap Array of Strings but instead of normal Array of String I see only address in memory of String in console.

val map = mapOf<String, Array<String>>()
val list = listOf("sport")
val array = list.toTypedArray()
map["key"] to array

And Array after this operation converts in smth like this — [Ljava.lang.String;@518ed9b4

But expected to see this kind of behavior:

map["key"] -> array("sport")

What's the problem might be with this sample of code?

Upvotes: -1

Views: 55

Answers (1)

broot
broot

Reputation: 28362

Arrays in Java/Kotlin don't have a good automatic conversion to strings (technically, their implementation of toString()). What you see is your array, but instead of showing the contents, it only says it is an array of strings and shows the memory address.

To show the contents of an array you can use builtin contentToString() extension or wrap it into a list:

println(arrayOf("sport").contentToString())
println(arrayOf("sport").asList())

BTW, I believe there is a mistake in your example. map["key"] to array doesn't do anything, it should be probably map["key"] = array. Also, map in your example is read-only, you can't add items to it. However, as you already got to the point you print an array, I assume your real code is a little different.

Upvotes: 3

Related Questions