Scala: getting the key (and value) of a Map.head e

2020-08-11 05:27发布

问题:

Let's imagine the following immutable Map:

val foo = Map((10,"ten"), (100,"one hundred"))

I want to get the key of the first element.

foo.head gets the first element. But what next?

I also want the value of this element, i.e. "ten"

回答1:

Set a key/value pair:
val (key, value) = foo.head



回答2:

Map.head returns a tuple, so you can use _1 and _2 to get its index and value.

scala> val foo = Map((10,"ten"), (100,"one hundred"))
foo: scala.collection.immutable.Map[Int,java.lang.String] = Map(10 -> ten, 100 -
> one hundred)

scala> val hd=foo.head
hd: (Int, java.lang.String) = (10,ten)

scala> hd._1
res0: Int = 10

scala> hd._2
res1: java.lang.String = ten