你能在 Scala 中使用自定义字符串插值字符吗?
Can you use a custom string interpolation character in Scala?
Scala 的 string interpolation 使用起来非常简单:
val user = "Bob"
val message = s"Hello, $user"
//Hello, Bob
对于包含大量财务数据的字符串块,这些通常需要双重转义,但是(对于大块,例如测试数据,可能会变长):
val user = "Mary"
val message = s"Balance owing for $user is 0"
//error: invalid string interpolation , expected: $$, $identifier or ${expression}
//error: unclosed string literal
val message = s"Balance owing for $user is $0"
//Balance owing for Mary is 0
是否可以使用不同的插值字符来避免双重转义?
val characterA = "Randolph"
val characterB = "Mortimer"
val family = "Duke"
val film = "Trading Places"
val outcome = "wagered"
val message = at"Your property was @{outcome} for by brothers @{characterA} and @{characterB} @{family}"
//Your property was wagered for by brothers Randolph and Mortimer Duke
您可以随时使用 format
方法:
val message = "Your property was %s for 1$ by brothers %s and %s %s"
println(message.format("actual outcome", "actual characterA", "actual characterB", "actual family"))
Is it possible to use a different interpolation character to avoid the double escape?
$
是 Scala syntax, however it is at least possible to define custom string interpolation 的一部分
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 0
Scala 的 string interpolation 使用起来非常简单:
val user = "Bob"
val message = s"Hello, $user"
//Hello, Bob
对于包含大量财务数据的字符串块,这些通常需要双重转义,但是(对于大块,例如测试数据,可能会变长):
val user = "Mary"
val message = s"Balance owing for $user is 0"
//error: invalid string interpolation , expected: $$, $identifier or ${expression}
//error: unclosed string literal
val message = s"Balance owing for $user is $0"
//Balance owing for Mary is 0
是否可以使用不同的插值字符来避免双重转义?
val characterA = "Randolph"
val characterB = "Mortimer"
val family = "Duke"
val film = "Trading Places"
val outcome = "wagered"
val message = at"Your property was @{outcome} for by brothers @{characterA} and @{characterB} @{family}"
//Your property was wagered for by brothers Randolph and Mortimer Duke
您可以随时使用 format
方法:
val message = "Your property was %s for 1$ by brothers %s and %s %s"
println(message.format("actual outcome", "actual characterA", "actual characterB", "actual family"))
Is it possible to use a different interpolation character to avoid the double escape?
$
是 Scala syntax, however it is at least possible to define custom string interpolation 的一部分
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 0