-
-
Save milessabin/a69d8ffbfe9f42e65fbf to your computer and use it in GitHub Desktop.
Scala string interpolation gives us a new kind of anonymous function literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
miles@lewis:~$ scala-trunk -Xexperimental | |
Welcome to Scala version 2.10.0.r25823-b20111012020224 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> val f = "Value of \{ _ : String} is \{ _ : Int }" | |
f: (String, Int) => String = <function2> | |
scala> f("foo", 23) | |
res0: String = Value of foo is 23 | |
scala> val g : (String, Int) => String = "Value of \{ _ } is \{ _ }" // Types can be inferred | |
g: (String, Int) => String = <function2> | |
scala> g("bar", 13) | |
res1: String = Value of bar is 13 | |
scala> def show[T](t : T)(f : T => String) = f(t) | |
show: [T](t: T)(f: T => String)String | |
scala> show(23)("> \{ _ } <") // Hole inferred as Int | |
res2: String = > 23 < | |
scala> show("wibble")("> \{ _ } <") // Hole inferred as String | |
res3: String = > wibble < |
@dscobal Is this stuff going to be in 2.10? I'd much prefer something like this over run-time errors the compiler can't see
"%d could be a number" format "bippy"
Most likely, though there's no compile time check of formatting strings. That is, I can write either of:
s"$bippy could be a number"
f"$bippy%d could be a number"
The first calls toString
on everything, whatever its type. The second uses formats, so it's subject to formatting casts errors.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@softprops This is not up-to-date, however, and underscores in the string templates are not presently supported.