Skip to content

Instantly share code, notes, and snippets.

@kevin-lee
Last active August 26, 2017 07:15
Show Gist options
  • Save kevin-lee/f3513cca50939668fc5e517faacf90b8 to your computer and use it in GitHub Desktop.
Save kevin-lee/f3513cca50939668fc5e517faacf90b8 to your computer and use it in GitHub Desktop.
Customized String interpolation example
/**
* @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""")
}
@damby
Copy link

damby commented Feb 16, 2017

z.z

@kevin-lee
Copy link
Author

@damby 😠

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