Nim*_*007 48 scala intellij-idea
无法转义函数中的所有引号
(它的基本用法 - >如果我发现一个字符串什么都不做,如果它不是一个字符串添加"在开头和结尾)
代码段:
def putTheDoubleQuotes(value: Any): Any = {
value match {
case s: String => s //do something ...
case _ => s"\"$value\"" //not working
}
}
Run Code Online (Sandbox Code Playgroud)
唯一有用的是:
case _ => s"""\"$ value \""""
这有更好的语法吗?
它看起来很糟糕,IDE(IntelliJ)标记为红色(但让你运行它真的很生气!!!!!)
abz*_*ing 37
这是Scala中的一个错误:
但也许你可以使用:
scala> import org.apache.commons.lang.StringEscapeUtils.escapeJava
import org.apache.commons.lang.StringEscapeUtils.escapeJava
scala> escapeJava("this is a string\nover two lines")
res1: java.lang.String = this is a string\nover two lines
Run Code Online (Sandbox Code Playgroud)
Ale*_*nov 28
您不需要在三引号字符串中转义引号,因此s""""$value"""""可以使用.不可否认,它看起来也不好看.
Sum*_*uma 20
另一个解决方案(在Scala跟踪器中也提到)是使用
case _ => s"${'"'}$value${'"'}"
Run Code Online (Sandbox Code Playgroud)
仍然很难看,但有时可能比三重引号更受欢迎.
似乎转发序列$"被建议作为SIP-24 for 2.12的一部分:
case _ => s"$"$value$""
Run Code Online (Sandbox Code Playgroud)
这个SIP从未被接受,因为它包含其他更有争议的建议.目前,努力$"在2.13中实现转义序列,因为Pre SIP/mini SIP $"在插值中逃脱".
对于您的用例,它们可以轻松实现良好的语法.
scala> implicit class `string quoter`(val sc: StringContext) {
| def q(args: Any*): String = "\"" + sc.s(args: _*) + "\""
| }
defined class string$u0020quoter
scala> q"hello,${" "*8}world"
res0: String = "hello, world"
scala> "hello, world"
res1: String = hello, world // REPL doesn't add the quotes, sanity check
scala> " hello, world "
res2: String = " hello, world " // unless the string is untrimmed
Run Code Online (Sandbox Code Playgroud)
松散隐藏在某个包对象的某个地方.
q当然,你可以为内插器命名.
上周,有人询问ML是否有能力使用反引号标识符.现在你可以做res3而不是res4:
scala> val `"` = "\""
": String = "
scala> s"${`"`}"
res3: String = "
scala> s"hello, so-called $`"`world$`"`"
res4: String = hello, so-called "world"
Run Code Online (Sandbox Code Playgroud)
刚刚发生的另一个想法是f-interpolator已经做了一些工作来按摩你的弦.例如,它必须智能地处理"%n".它可以同时处理一个额外的转义"%q",它不会传递给底层格式化程序.
那看起来像是:
scala> f"%qhello, world%q"
<console>:9: error: conversions must follow a splice; use %% for literal %, %n for newline
Run Code Online (Sandbox Code Playgroud)
这值得一个增强请求.
更新:刚刚注意到在插值中不推荐使用octals:
scala> s"\42hello, world\42"
res12: String = "hello, world"
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题,我测试了这个,这就是我使用的.
raw"""
Inside this block you can put "as many" quotes as you "want" and even "${5 + 7}" interpolate inside the quotes
"""
Run Code Online (Sandbox Code Playgroud)
http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-raw-interpolator
一个例子:
scala> val username="admin"
> username: String = admin
scala> val pass="xyz"
> pass: String = xyz
scala> println(s"""{"username":"$username", "pass":"$pass"}""")
> {"username":"admin", "pass":"xyz"}
Run Code Online (Sandbox Code Playgroud)
简单的方法:-
val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes
Run Code Online (Sandbox Code Playgroud)