如何在scala中使用插值将双引号插入到String中

 糖糖菓子 发布于 2023-02-03 12:24

无法转义函数中的所有引号

(它的基本用法 - >如果我发现一个字符串什么都不做,如果它不是一个字符串添加"在开头和结尾)

代码段:

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

唯一有用的是:

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

这有更好的语法吗?

它看起来很糟糕,IDE(IntelliJ)标记为红色(但让你运行它真的很生气!!!!!)

6 个回答
  • 对于您的用例,它们可以轻松实现良好的语法.

    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当然,你可以为内插器命名.

    上周,有人询问ML是否有能力使用反引号标识符.现在你可以做res3而不是res4:

    scala> val `"` = "\""
    ": String = "
    
    scala> s"${`"`}"
    res3: String = "
    
    scala> s"hello, so-called $`"`world$`"`"
    res4: String = hello, so-called "world"
    

    刚刚发生的另一个想法是f-interpolator已经做了一些工作来按摩你的弦.例如,它必须智能地处理"%n".它可以同时处理一个额外的转义"%q",它不会传递给底层格式化程序.

    那看起来像是:

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

    这值得一个增强请求.

    更新:刚刚注意到在插值中不推荐使用octals:

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

    2023-02-03 12:27 回答
  • 您不需要在三引号字符串中转义引号,因此s""""$value"""""可以使用.不可否认,它看起来也不好看.

    2023-02-03 12:27 回答
  • 这是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
    

    2023-02-03 12:27 回答
  • 另一个解决方案(在Scala跟踪器中也提到)是使用

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

    仍然很难看,但有时可能比三重引号更受欢迎.

    似乎转发序列$"被建议作为SIP-24 for 2.12的一部分:

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

    这个SIP从未被接受,因为它包含其他更有争议的建议.目前,努力$"在2.13中实现转义序列,因为Pre SIP/mini SIP $"在插值中逃脱".

    2023-02-03 12:27 回答
  • 这解决了我的问题,我测试了这个,这就是我使用的.

    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

    2023-02-03 12:27 回答
  • 如前所述,这是Scala中的一个已知错误.解决方法是使用\042.

    2023-02-03 12:27 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有