Last active
August 26, 2017 07:15
-
-
Save kevin-lee/f3513cca50939668fc5e517faacf90b8 to your computer and use it in GitHub Desktop.
Customized String interpolation example
This file contains 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
/** | |
* @author Kevin Lee | |
* @since 2016-04-09 | |
*/ | |
object StringInterpolation extends App { | |
implicit class EscapeNewLineAndDoubleQuote(val sc: StringContext) extends AnyVal { | |
def esc(args: Any*): String = { | |
val strings = sc.parts.iterator | |
val expression = args.iterator | |
val builder = new StringBuilder(strings.next) | |
while (strings.hasNext) { | |
builder append expression.next.toString.replaceAllLiterally("\n", "\\n").replaceAllLiterally("\r", "\\r").replaceAllLiterally("\"", """\"""") | |
builder append strings.next | |
} | |
builder.toString | |
} | |
} | |
private val nl = "\n" | |
private val dq = "\"" | |
// blah blah\nblah \"blah\"\nblah | |
println(esc"blah blah\nblah ${dq}blah${dq}${nl}blah") | |
// blah blah\nblah \"blah\"\nblah | |
println(esc"""blah blah\nblah ${dq}blah${dq}${nl}blah""") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@damby 😠