Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: why can't I map a function accepting Seq[Char] over a collection of Strings

I can define a function that accepts a Seq[Char]

def f(s: Seq[Char]) = s

and it works if I pass in a String:

scala> f("this")
res8: Seq[Char] = this

which means that I can use it in a map:

scala> List("this").map(s => f(s))
res9: List[Seq[Char]] = List(this)

So why can't I do this?:

scala> List("this").map(f)
<console>:10: error: type mismatch;
 found   : Seq[Char] => Seq[Char]
 required: java.lang.String => ?
              List("this").map(f)
                               ^
like image 702
dhg Avatar asked Aug 04 '12 19:08

dhg


2 Answers

You can't do that because there is no promotion of an implicit conversion A => B to F[A] => F[B]. In particular, f is actually an instance of type Seq[Char] => Seq[Char], and you would require that the implicit conversion from String => Seq[Char] would generate a function String => Seq[Char]. Scala doesn't do two-step implicit conversions such as this.

If you write s => f(s), Scala is free to fiddle with the types so that s is converted to Seq[Char] before being passed in to f.

like image 123
Rex Kerr Avatar answered Oct 25 '22 21:10

Rex Kerr


Perhaps the best way to solve this is:

def f[S <% Seq[Char]](s: S): S = /* some code */

Then, map and friends will work as expected.

like image 41
Ptharien's Flame Avatar answered Oct 25 '22 21:10

Ptharien's Flame