Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala weird map function behaviour

Tags:

scala

Why does the following code work?

scala> List(1,2,3) map "somestring"
res0: List[Char] = List(o, m, e)

It works in both 2.9 and 2.10. Looking into the typer:

[master●●] % scala -Xprint:typer -e 'List(1,2,3) map "somestring"'                                                                                ~/home/folone/backend
[[syntax trees at end of                     typer]] // scalacmd2632231162205778968.scala
package <empty> {
  object Main extends scala.AnyRef {
    def <init>(): Main.type = {
      Main.super.<init>();
      ()
    };
    def main(argv: Array[String]): Unit = {
      val args: Array[String] = argv;
      {
        final class $anon extends scala.AnyRef {
          def <init>(): anonymous class $anon = {
            $anon.super.<init>();
            ()
          };
          immutable.this.List.apply[Int](1, 2, 3).map[Char, List[Char]](scala.this.Predef.wrapString("somestring"))(immutable.this.List.canBuildFrom[Char])
        };
        {
          new $anon();
          ()
        }
      }
    }
  }
}

Looks like it gets converted to the WrappedString, which has an apply method. This explains, how it works, but does not explain, how a WrappedString got accepted into a parameter of type A => B (as specified in the scaladoc). Can someone explain, how this happens, please?

like image 756
George Avatar asked Sep 25 '26 15:09

George


1 Answers

By way of collection.Seq[Char], which is a subtype of PartialFunction[Int, Char], which is a subtype of Int => Char:

scala> implicitly[collection.immutable.WrappedString <:< (Int => Char)]
res0: <:<[scala.collection.immutable.WrappedString,Int => Char] = <function1>

So there's only one implicit conversion happening—the original String => WrappedString, which kicks in because we're treating a string like a function.

like image 67
Travis Brown Avatar answered Sep 28 '26 14:09

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!