4

我想知道在scala中进行字符串插值时是否有任何方法可以保留缩进。本质上,我想知道是否可以插入自己的 StringContext。宏会解决这个问题,但我想等到它们正式发布。

这就是我要的:

val x = "line1 \nline2"
val str = s">       ${x}"

str 应该评估为

>       line1
        line2
4

4 回答 4

8

回答我的问题,并将 Daniel Sobral 非常有用的答案转换为代码。希望它对遇到相同问题的其他人有用。我还没有使用隐式类,因为我仍然是 2.10 之前的版本。

用法:

import Indenter._并像这样使用字符串插值e" $foo "

例子
import Indenter._

object Ex extends App {
  override def main(args: Array[String]) {
    val name = "Foo"
    val fields = "x: Int\ny:String\nz:Double"
    // fields has several lines. All of them will be indented by the same amount.
    print (e"""
        class $name {
           ${fields}
        }
        """)  
  }
}

应该打印

class Foo
   x: Int
   y: String
   z: Double

这是自定义缩进上下文。

class IndentStringContext(sc: StringContext) {
  def e(args: Any*):String = {
    val sb = new StringBuilder()
    for ((s, a) <- sc.parts zip args) {
      sb append s
      
      val ind = getindent(s)
      if (ind.size > 0) { 
        sb append a.toString().replaceAll("\n", "\n" + ind)
      } else {
        sb append a.toString()
      }
    }
    if (sc.parts.size > args.size)
      sb append sc.parts.last
      
    sb.toString()
  }
  
  // get white indent after the last new line, if any
  def getindent(str: String): String = {
    val lastnl = str.lastIndexOf("\n")
    if (lastnl == -1) ""
    else {
      val ind = str.substring(lastnl + 1)
      if (ind.trim.isEmpty) ind  // ind is all whitespace. Use this
      else ""
    }
  }
}

object Indenter {
  // top level implicit defs allowed only in 2.10 and above
  implicit  def toISC(sc: StringContext) = new IndentStringContext(sc)
}
于 2012-07-11T06:05:09.127 回答
5

您可以编写自己的插值器,也可以使用自己的插值器遮蔽标准插值器。现在,我不知道您的示例背后的语义是什么,所以我什至不打算尝试。

查看我在Slideshare或SpeakerDeck上关于 Scala 2.10 的演示文稿,因为它们包含有关您可以编写/覆盖插值器的所有方式的示例。从幻灯片 40 开始(目前——演示文稿可能会更新到 2.10 最终发布)。

于 2012-07-10T00:50:42.967 回答
0

对于任何寻求 2.10 后答案的人:

object Interpolators {
  implicit class Regex(sc: StringContext) {
    def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
  }

  implicit class IndentHelper(val sc: StringContext) extends AnyVal {
    import sc._

    def process = StringContext.treatEscapes _

    def ind(args: Any*): String = {
      checkLengths(args)
      parts.zipAll(args, "", "").foldLeft("") {
        case (a, (part, arg)) =>
          val processed = process(part)

          val prefix = processed.split("\n").last match {
            case r"""([\s|]+)$d.*""" => d
            case _                   => ""
          }

          val argLn = arg.toString
            .split("\n")

          val len = argLn.length

          // Todo: Fix newline bugs
          val indented = argLn.zipWithIndex.map {
            case (s, i) =>
              val res = if (i < 1) { s } else { prefix + s }
              if (i == len - 1) { res } else { res + "\n" }
          }.mkString

          a + processed + indented
      }
    }
  }
}
于 2019-02-14T18:03:17.223 回答
0

这是一个简短的解决方案。Scastie上的完整代码和测试。那里有两个版本,一个普通的indented插值器,还有一个稍微复杂一点的indentedWithStripMargin插值器,使其更具可读性:

assert(indentedWithStripMargin"""abc               
                                |123456${"foo\nbar"}-${"Line1\nLine2"}""" == s"""|abc
                                                                                 |123456foo
                                                                                 |      bar-Line1
                                                                                 |          Line2""".stripMargin)

这里是核心功能:

  def indentedHelper(parts: List[String], args: List[String]): String = {
    // In string interpolation, there is always one more string than argument
    assert(parts.size == 1+args.size)

    (parts, args) match {
      // The simple case is where there is one part (and therefore zero args). In that case,
      // we just return the string as-is:
      case (part0 :: Nil, Nil) => part0
      // If there is more than one part, we can simply take the first two parts and the first arg,
      // merge them together into one part, and then use recursion. In other words, we rewrite
      //    indented"A ${10/10} B ${2} C ${3} D ${4} E"
      // as
      //           indented"A 1 B ${2} C ${3} D ${4} E"
      // and then we can rely on recursion to rewrite that further as:
      //              indented"A 1 B 2 C ${3} D ${4} E"
      // then:
      //                 indented"A 1 B 2 C 3 D ${4} E"
      // then:
      //                    indented"A 1 B 2 C 3 D 4 E"
      case (part0 :: part1 :: tailparts, arg0 :: tailargs) => {
        // If 'arg0' has newlines in it, we will need to insert spaces. To decide how many spaces,
        // we count many characters after after the last newline in 'part0'. If there is no
        // newline, then we just take the length of 'part0':
        val i = part0.reverse.indexOf('\n')
        val n = if (i == -1)
                  part0.size // if no newlines in part0, we just take its length
                else
                  i // the number of characters after the last newline
        // After every newline in arg0, we must insert 'n' spaces:
        val arg0WithPadding = arg0.replaceAll("\n", "\n" + " "*n)
        val mergeTwoPartsAndOneArg = part0 + arg0WithPadding + part1
        // recurse:
        indentedHelper(mergeTwoPartsAndOneArg :: tailparts, tailargs)
      }
      // The two cases above are exhaustive, but the compiler thinks otherwise, hence we need
      // to add this dummy.
      case _ => ???
    }
  }
于 2020-04-09T23:37:09.260 回答