dhg
dhg

Reputation: 52691

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)
                               ^

Upvotes: 13

Views: 806

Answers (2)

Ptharien&#39;s Flame
Ptharien&#39;s Flame

Reputation: 3246

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.

Upvotes: 3

Rex Kerr
Rex Kerr

Reputation: 167901

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.

Upvotes: 11

Related Questions