What's the difference between raw string interpolation and triple quotes in scala

后端 未结 2 1500
遥遥无期
遥遥无期 2020-12-23 19:37

Scala has triple quoted strings \"\"\"String\\nString\"\"\" to use special characters in the string without escaping. Scala 2.10 also added raw\"String\\n

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-23 20:08

    Looking at the source for the default interpolators (found here: https://github.com/scala/scala/blob/2.11.x/src/library/scala/StringContext.scala) it looks like the "raw" interpolator calls the identity function on each letter, so what you put in is what you get out. The biggest difference that you will find is that if you are providing a string literal in your source that includes the quote character, the raw interpolator still won't work. i.e. you can't say

    raw"this whole "thing" should be one string object"
    

    but you can say

    """this whole "thing" should be one string object"""
    

    So you might be wondering "Why would I ever bother using the raw interpolator then?" and the answer is that the raw interpolator still performs variable substitution. So

    val helloVar = "hello"
    val helloWorldString = raw"""$helloVar, "World"!\n"""
    

    Will give you the string "hello, "World"!\n" with the \n not being converted to a newline, and the quotes around the word world.

提交回复
热议问题