Skip to content

Instantly share code, notes, and snippets.

@sofoklis sofoklis/customsi.scala
Last active Jan 10, 2018

Embed
What would you like to do?
Custom string interpolation
object Test {
// Implicit class is also a new feature in scala 2.10
implicit class CounterSC(val sc: StringContext) extends AnyVal {
// Define functions that we want to use with string interpolation syntax
def partsCount(args: Any*): Int = sc.parts.length
def argsCount(args: Any*): Int = args.length
def tokenCount(args: Any*): Int = sc.parts.length + args.length
def getParts(args: Any*): String =
s"parts: ${sc.parts.mkString(",")}"
def getArgs(args: Any*): String =
s"args: ${args.mkString(",")}"
}
def main(args: Array[String]) {
val value = "value"
val num = 3
// Use the functions that we created when the implicit class is in scope
val i = tokenCount"Scala $num interpolation ${1 + 1} lastarg $value"
val p = partsCount"Scala $num interpolation ${1 + 1} lastarg $value"
val a = argsCount"Scala $num interpolation ${1 + 1} lastarg $value"
val parts = getParts"Scala $num interpolation ${1 + 1} lastarg $value"
val arg = getArgs"Scala $num interpolation ${1 + 1} lastarg $value"
println(s"token count: $i") // token count: 7
println(s"args count: $a") // args count: 3
println(arg) // args: 3,2,value
println(s"parts count: $p") // parts count: 4
println(parts) // parts: Scala , interpolation , lastarg ,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.