Skip to content

Instantly share code, notes, and snippets.

@pedrofurla
Last active June 11, 2016 15:06
Show Gist options
  • Save pedrofurla/d399c76c68c9b4e03283fe121c7afbb5 to your computer and use it in GitHub Desktop.
Save pedrofurla/d399c76c68c9b4e03283fe121c7afbb5 to your computer and use it in GitHub Desktop.
Where String#+ comes from?
object Tmp {
"zzz" ++ "kkk" // Fails with -Yno-predef
// after typer the above is scala.this.Predef.augmentString("zzz").++[Char, String](scala.this.Predef.augmentString("kkk"))(scala.this.Predef.StringCanBuildFrom);
"aaa"+new Object() // Doesn't fail ever!
// after typer the above is "aaa".+(new java.this.lang.Object());
// Why didn't `+` desugar to something else?
new Object() + "aaa" // Fails with -Yno-predef
// after typer the above is scala.this.Predef.any2stringadd[Object](new java.this.lang.Object()).+("aaa");
// import Predef.{any2stringadd => _, StringAdd => _, augmentString => _, _}
}
@pedrofurla
Copy link
Author

[[syntax trees at end of                   cleanup]] // tmp.scala
package <empty> {
  object Tmp extends Object {
    def <init>(): Tmp.type = {
      Tmp.super.<init>();
      new collection.immutable.StringOps(scala.this.Predef.augmentString("zzz")).++(new collection.immutable.StringOps(scala.this.Predef.augmentString("kkk")), scala.this.Predef.StringCanBuildFrom());
      "aaa".+(new Object());
      Predef$any2stringadd.this.+$extension(scala.this.Predef.any2stringadd(new Object()), "aaa");
      ()
    }
  }
}

@demobox
Copy link

demobox commented May 12, 2016

See http://www.scala-lang.org/files/archive/spec/2.11/12-the-scala-standard-library.html#class-string:

"Scala's String class is usually derived from the standard String class of the underlying host system (and may be identified with it). For Scala clients the class is taken to support in each case a method

def + (that: Any): String

which concatenates its left operand with the textual representation of its right operand."

@pedrofurla
Copy link
Author

@demobox, it doesn't explains how to compiler ends up compiling it into StringBuilder#append.

@dwijnand
Copy link

@pedrofurla
Copy link
Author

Awesome, cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment