Last active
January 10, 2018 10:01
-
-
Save sofoklis/4612013 to your computer and use it in GitHub Desktop.
Custom string interpolation
This file contains hidden or 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
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