Why does IntelliJ Idea offer to enclose a string literal to triple double quotes?

半腔热情 提交于 2019-12-11 10:25:26

问题


While using IntelliJ Idea to code Scala I've noticed it to use to offer to enclose a string literal in a second pair of double quotes. «Convert to """string"""» - it says. If I agree - it just adds a 2 more double quote marks before and 2 more after the string, having my string to look like

val myString = """my string value"""

How does this make any sense? Do triple double quotes mean something special in Scala?


回答1:


With IntelliJ smart String, there should be only two cases.

  • simple string (which you can convert to triple double-quotes multi-line String literal)
  • multi-line String literal, introduced way back in Scala 2.1.7 (which you can convert back to a single String)

So when you see this:

you should end up with """. If not, this should be reported as a bug in the youtrack Scala project.


But if there were triple double quotes, then IntelliJ correctly transformed your simple String into a multi-line String literal, which, as illustrated by langref, allows you to define:

val text = "This\nIs\nA\nMultiline\nString"

into

val text = """This
Is
A
Multiline
String"""

Rosetta code mentions the behavior has changed between Scala 2.7 and 2.8:

on version 2.7, the triple-double-quoted string ends at the third consecutive quote, on version 2.8 it ends on the last quote of a series of at least three double-quotes.

Scala 2.7:

scala> val error = """can't finish with a quote: """"
<console>:1: error: unterminated string
       val error = """can't finish with a quote: """"
                                                    ^

Scala 2.8

scala> val success = """but it can on 2.8: """"
success: java.lang.String = but it can on 2.8: "



回答2:


Triple quotes are used to contain raw strings.

A raw string can contain any character, including newlines (as illustrated by @VonC) but also escape sequences in general.

One common usage is in simplifying regular expression patterns, for example:

val Date = """((\d\d)/(\d\d)/(\d{4}))|((\w{3}) (\d\d),\s?(\d{4}))""".r

instead of

val Date = "((\\d\\d)/(\\d\\d)/(\\d{4}))|((\\w{3}) (\\d\\d),\\s?(\\d{4}))".r  

Not a large difference really but making regex's simpler is usually appreciated.



来源:https://stackoverflow.com/questions/8024245/why-does-intellij-idea-offer-to-enclose-a-string-literal-to-triple-double-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!