Scala对象为文字

时间:2014-03-26 22:38:04

标签: scala literals

我有一个对象,它是一个案例类的集合。这就是打印的样子。

Sentence(List(),List(Word(Anarchism,Anarchism,NNP,I-NP,O,N), Word(.,.,.,O,O,.)))

是否可以生成生成此对象的scala文字?实际示例更复杂,还包括一堆需要转义的字符。预期的输出类似于

Sentence(Seq(), Seq(Word("Anarchism", "Anarchism", "NNP", "I-NP", "O", "N"), Word(".", ".", ".", "O", "O", ".")))

1 个答案:

答案 0 :(得分:2)

这样的事情:

def scalaCodeForObject(x: Any): String = x match {
  // handle primitives
  case s: String =>
    // trim is used to make the strings clearer
    val escaped = s.replaceAll("""\""", """\\""").replaceAll(""" " """.trim, """ \" """.trim)
    s""" "$escaped" """.trim
  case i: Int => i.toString
  ...
  // all case classes are Products
  case p: Product =>
    val className = x.getClass.getSimpleName
    val fields = p.productIterator
    fields.map(scalaCodeForObject _).mkString(", ", className + "(", ")")
  // handle other cases you need, e.g. lists, other seqs, maps, etc.
}