Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active June 8, 2016 22:11
Show Gist options
  • Save fancellu/7e76ce10dcb969384357 to your computer and use it in GitHub Desktop.
Save fancellu/7e76ce10dcb969384357 to your computer and use it in GitHub Desktop.
Very simple example of Scala "string" Interpolation (more than just strings though)
//http://docs.scala-lang.org/overviews/core/string-interpolation.html
implicit class MyQuote(ctx:StringContext){
def x(args:String*):String=ctx.parts.zip(args).map{case (p,a)=>s"$p$a"}.mkString("")
}
val string="STRINGY"
val string2="STRINGY2"
println(x"Part1 $string Part2 $string2 Part3 $string")
// Part1 STRINGY Part2 STRINGY2 Part3 STRINGY
// Added splicing example
implicit class MyQuote(ctx:StringContext){
def x[T](args:T*):String={ctx.parts.zip(args).map{
case (p,a:Seq[T]) if (p.endsWith(".."))=>p.replaceAll("""..$""","")+a.mkString(",")
case (p,a)=>s"$p$a"
case _=>""
}.mkString("")
}
}
val string="STRINGY"
val string2="STRINGY2"
val strings=List("one","two","three")
println(x"Part1 $string Part2 $string2 Part3 $string List of Strings:..$strings")
// Part1 STRINGY Part2 STRINGY2 Part3 STRINGY List of Strings:one,two,three
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment