如何插入双引号到字符串与插值在 Scala

在转义函数中的所有引号时遇到麻烦

(it 的基本用法-> if i find a string do nothing,if it not a string add)

代码片段:

  def putTheDoubleQuotes(value: Any): Any = {
value match {
case s: String => s //do something ...
case _  => s"\"$value\"" //not working
}
}

唯一奏效的就是:

Case _ = > s“”“ $value”“”

有更好的语法吗?

它看起来很糟糕,IDE (IntelliJ)将它标记为红色(但是让你运行它,这真的让我很恼火!)

57756 次浏览

这是 Scala 中的一个 bug:

转义不与字符串插值工作

但也许你可以用:

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

您不需要在三重引号字符串中转义引号,所以 s""""$value"""""将工作。

对于您的用例,它们使得实现漂亮的语法变得容易。

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

将隐式对象放在某个包对象中。

当然,除了 q之外,您还可以为插值器命名。

上周,有人要求机器学习能够使用反引号标识符。现在你可以做 res3但不能做 res4:

scala> val `"` = "\""
": String = "


scala> s"${`"`}"
res3: String = "


scala> s"hello, so-called $`"`world$`"`"
res4: String = hello, so-called "world"

我刚刚想到的另一个想法是,f-插值器已经做了一些工作来按摩你的字符串。例如,它必须智能地处理“% n”。同时,它可以处理一个额外的转义“% q”,这个转义不会传递给底层格式化程序。

看起来像是:

scala> f"%qhello, world%q"
<console>:9: error: conversions must follow a splice; use %% for literal %, %n for newline

这值得提出强化请求。

更新: 刚刚注意到八进制在插值中还没有被弃用:

scala> s"\42hello, world\42"
res12: String = "hello, world"

另一种解决方案(也在 Scala 追踪器中提到)是使用

case _ => s"${'"'}$value${'"'}"

虽然还是很难看,但有时候可能比三重引号更受欢迎。

这似乎是一个逃逸序列 $"被建议作为2.12 SIP-24的一部分:

case _ => s"$"$value$""

这个 SIP 从未被接受,因为它包含了其他更具争议性的建议。目前正在努力使转义序列 $"在2.13中实现为 插值中的 Pre SIP/mini SIP $”转义

怎么样

s"This is ${"\"" + variable + "\""}" inserted in string with quotes

这为我解决了问题,我测试了这个,这是我使用的。

raw"""
Inside this block you can put "as many" quotes as you "want" and even "${5 + 7}" interpolate inside the quotes
"""

Http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-raw-interpolator

正如前面提到的,这是 Scala 中的一个已知错误。一个变通方法是使用 \042

它在我的案例中被大量使用,因此我创建了这个版本:

object StringUtil{
implicit class StringImprovements(s: String) {
def quoted = "\""+s+"\""
}
}


val myStatement = s"INSERT INTO ${tableName.quoted} ..."

进一步采纳@Pascalius 的建议。

object StringUtil{
implicit class StringImprovements(val s: String) extends AnyVal {
def dqt = "\""+s+"\""    // double quote
def sqt = s"'$s'"        // single quote
}
}

Scala 只使用 StringReform 类创建一个中间对象,在该对象上隐式调用两个扩展方法 dqt & sqt。不过,我们可以通过使该类继承 AnyVal 来消除此对象的创建并提高性能。因为 Scala 提供了值类型,特别是在这种情况下,编译器将通过直接调用方法来替换对象。

下面是一个简单的示例,在混合中使用上面的隐式类,其中我们使用命名变量(string & boolean)和插值字符串中的函数。

import StringUtil._
abstract class Animal {
...
override def toString(): String = s"Animal:${getFullName().dqt}, CanFly:$canFly, Sound:${getSound.dqt}"
}

简单的方法:-

val str="abc"
println(s"$str") //without double quotes
println(s"""\"$str\"""") // with double quotes

举个例子:

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"}

启动 Scala 2.13.6转义双引号 工作符合字符串插值的预期

Welcome to Scala 2.13.6 (OpenJDK 64-Bit Server VM, Java 15.0.2).
Type in expressions for evaluation. Or try :help.


scala> s"\"Hello\""
val res0: String = "Hello"


scala> s"$"Hello$""
val res1: String = "Hello"