-
-
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 < |
I'm loving this direction.
@softprops This is not up-to-date, however, and underscores in the string templates are not presently supported.
@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
For whatever it is worth, I prefer {. Sure, it is not the same as other languages, but it seems every single feature Scala added "to be like Java" turned out to be a dubious decision at best, and a weighty stone chained at its feet as it struggles forward at worst. So I have a pretty high bar for "to be like X" features.
Using { has two advantages:
Yes, { is not natural for me either, but I'm sure just a couple of months seeing it and I'll be completely at ease. And I do like the "escape" nature of it, as it indicates a place where a different processing takes place.