Search code examples
stringscalainterpolationstring-interpolation

Can you use a custom string interpolation character in Scala?


Scala's string interpolation is pretty straight forward to use:

val user = "Bob"
val message = s"Hello, $user"
//Hello, Bob

For string blocks containing lots of financial data, these normally need double escaping, however (which for large blocks, such as test data, might get long):

val user = "Mary"
val message = s"Balance owing for $user is $100"
//error: invalid string interpolation $1, expected: $$, $identifier or ${expression}
//error: unclosed string literal
val message = s"Balance owing for $user is $$100"
//Balance owing for Mary is $100

Is it possible to use a different interpolation character to avoid the double escape?

val characterA = "Randolph"
val characterB = "Mortimer"
val family = "Duke"
val film = "Trading Places"
val outcome = "wagered"
val message = at"Your property was @{outcome} for $1 by brothers @{characterA} and @{characterB} @{family}"
//Your property was wagered for $1 by brothers Randolph and Mortimer Duke

Solution

  • Is it possible to use a different interpolation character to avoid the double escape?

    $ is part of Scala syntax, however it is at least possible to define custom string interpolation along the lines

    scala> implicit class DollarSignInterpolation(val sc: StringContext) {
         |   def usd(args: Any*): String =
         |     sc.s(args:_*).replace("USD", "$")
         | }
    class DollarSignInterpolation
    
    scala> val user = "Mary"
    val user: String = Mary
    
    scala> usd"""Balance owing for $user is USD100"""
    val res0: String = Balance owing for Mary is $100