Skip to content

Instantly share code, notes, and snippets.

@tototoshi
Created July 17, 2012 14:52
Show Gist options
  • Save tototoshi/3129873 to your computer and use it in GitHub Desktop.
Save tototoshi/3129873 to your computer and use it in GitHub Desktop.
trying string interpolation in scala 2.10
/* SIP11 https://docs.google.com/document/d/1NdxNxZYodPA-c4MLr33KzwzKFkzm9iW9POexT9PkJsU/edit?hl=en_US */
toshi@/home/toshi% ./opt/scala-2.10.0-M5/bin/scala
Welcome to Scala version 2.10.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_32).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val n = 10
n: Int = 10
scala> "Bob is " + n + " years old"
res0: String = Bob is 10 years old
scala> "Bob is $n ears old"
res1: String = Bob is $n ears old
scala> s"Bob is $n ears old"
res2: String = Bob is 10 ears old
scala> s"Bob is ${n} ears old"
res3: String = Bob is 10 ears old
scala> f"Bob is $n%03d ears old"
res4: String = Bob is 010 ears old
scala> val hello = "Hello, World!"
hello: String = Hello, World!
scala> implicit class XMLinterpolation(s: StringContext) {
| object xml {
| def apply(exprs: Any*) = <span>{exprs}</span>
| }
| }
defined class XMLinterpolation
scala> xml"<span>$hello</span>"
res15: scala.xml.Elem = <span>Hello, World!</span>
@fernandoracca
Copy link

better still, try this:

implicit class XmlHelper(val sc: StringContext) extends AnyVal {
def xml(exprs: Any*): scala.xml.Elem = {exprs}
}

update: unfortunately i can't write the xml tags in this post, only in the gist file. but works exactly as in your original code, only that it doesn't create a class.

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