I have a map:
val mnem = Map(
'2' -> "ABC", '3' -> "DEF", '4' -> "GHI", '5' -> "JKL",
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", '9' -> "WXYZ")
I'm curious why I can't pass this map as a mapping function considering that a Map is both a collection and a function such as below
val digits = "2345" //> digits : String = 2345
digits flatMap mnem //> ERROR
But I can do this
digits flatMap(mnem(_)) //> res0: String = ABCDEFGHIJKL
I was trying to do something analogous to this:
digits map mnem //> res1: scala.collection.immutable.IndexedSeq[String] = Vector(ABC, DEF, GHI,
//| JKL)
Map[Char, String] is a function (Char => String).
trait Map[A, +B] extends ... MapLike[A, B, Map[A, B]]
trait MapLike[A, +B, ...] extends PartialFunction[A, B] ...
trait PartialFunction[-A, +B] extends (A) ⇒ B
This works fine:
val f: Char => String = mnem
You'll get the same error with digits flatMap f.
flatMap on String takes Char ⇒ GenTraversableOnce[B] as parameter. And String is not a GenTraversableOnce, so (Char => String) (and Map[Char, String]) is not Char ⇒ GenTraversableOnce[B].
Scala rewrites Map.apply and Map(_) as x => Map(x) and then applies an implicit conversion to function result:
x => augmentString(Map(x))
It can convert Map(x) to get function of type Char ⇒ GenTraversableOnce[Char], but it can't convert existing function of type Char => String to Char ⇒ GenTraversableOnce[Char] since there is no such implicit conversion is scope.
To get the equivalent of the line
digits flatMap(mnem(_)) // mnem's apply method is the actual method passed to flatMap
you want
digits flatMap mnem.apply
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With