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