Student - MapOf question

Hi there,

Could someone point me to or explain how I would access a specific key in a multilayered map.

Here is a sample:

val letters = mapOf(
“A” to
Letter(
name = “A”,
description = “Apple”
),
“B” to
Letter(
name = “B”,
description = “Banana”
))

If I wanted to access the description of B. How would that look?

Val bdesc = letters[“B”].Letter.description?

It depends on your approach, but for example you can use one of those options:

val bdesc = letters["B"]?.description // null-safe way
val bdesc = letters["B"]!!.description // forceful way
val bdesc = letters.getValue("B").description // forceful way 2
1 Like

I won’t have to reference to Letter? The instance holding the information for “B”. Where letters is the map.

No, .Letter doesn’t make sense here. There is no object with Letter property. Similarly, you don’t access the map of letters with letters.Map, but just letters.

1 Like

The map maps strings to objects of type Letter. So letters["B"] returns a Letter, and you can access the Letter's fields directly.

1 Like