Scala: Seq, Map and Set as functions
Posted: | Categories: Programming, Scala | Tags: Collections, Function, List, Map, Partial Function, Seq, Set, Vector
Yesterday my mate asked me: “I have a List[String]
and a Map[String, Int]
and I want
a List[Int]
where its values are those of the Map
whose keys match the List[String]
elements,
maintaining the order. Should I use pattern matching?”. I know, the sentence is a bit convoluted but the
code will make it clear, hopefully. Anyway, I replied: “No, you don’t need pattern matching, you just need this”:
scala> val m = Map("a" -> 1, "b" -> 2, "c" -> 3)
m: scala.collection.immutable.Map[String,Int] =
Map(a -> 1, b -> 2, c -> 3)
scala> val l = List("a", "c", "b")
l: List[String] = List(a, c, b)
scala> l collect m
res0: List[Int] = List(1, 3, 2)
Hold on, how does it work? If you look at the definition of the collect
method you’ll see it accepts a
PartialFunction
, instead I passed a Map
to it.
Well, it turns out that Map
is a PartialFunction
.