Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created October 12, 2011 11:33
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milessabin/a69d8ffbfe9f42e65fbf to your computer and use it in GitHub Desktop.
Save milessabin/a69d8ffbfe9f42e65fbf to your computer and use it in GitHub Desktop.
Scala string interpolation gives us a new kind of anonymous function literal
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 <
@dcsobral
Copy link

@softprops

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