说我有以下两个case classes:
case class Address(street: String, city: String, state: String, zipCode: Int)
case class Person(firstName: String, lastName: String, address: Address)
Run Code Online (Sandbox Code Playgroud)
和以下Person类的实例:
val raj = Person("Raj", "Shekhar", Address("M Gandhi Marg",
"Mumbai",
"Maharashtra",
411342))
Run Code Online (Sandbox Code Playgroud)
现在,如果我想更新zipCode,raj那么我将不得不做:
val updatedRaj = raj.copy(address = raj.address.copy(zipCode = raj.address.zipCode + 1))
Run Code Online (Sandbox Code Playgroud)
随着嵌套水平的提高,这将变得更加丑陋.是否有更清洁的方式(像Clojure的东西update-in)来更新这样的嵌套结构?
我有这样的NodeSeq:
<foo>
<baz><bar key1="value1" key2="value2">foobar</bar></baz>
Blah blah blah
<bar key1="value3">barfoo</bar>
</foo>
我想为所有bars'属性添加一个新属性.我现在正在做:
val rule = new RewriteRule() {
override def transform(node: Node): Seq[Node] = {
node match {
case Elem(prefix, "bar", attribs, scope, content@_*) => Elem(prefix, "bar", attribs append Attribute(None, "newKey", Text("newValue"), scala.xml.Null) , scope, content:_*)
case other => other
}
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是它只适用于1个节点.我希望它以递归方式处理所有节点,如果我在for循环中调用转换,我不能用新值替换它们,因为它们变得不可变.我怎么解决这个问题?
我正在编写一个工具来使用scala更新一些xml文件(本例中为pom.xml),因为它在java中的工作量明显高于(理论上)scala.我可以很好地解析xml文件,但我需要替换现有xml中的节点并重写结果.例如:
<dependency>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
所以我想找到这样的所有节点并将其替换为:
<dependency>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<version>1.0</version> <!-- notice the lack of -SNAPSHOT here -->
</dependency>
Run Code Online (Sandbox Code Playgroud)
所以,我可以简单地获得所有版本节点,但是如何用我想要的节点替换它们?
// document is already defined as the head of the xml file
nodes = for (node <- document \\ "version"; if (node.text.contains("SNAPSHOT"))) yeild node
Run Code Online (Sandbox Code Playgroud)
那我想做点什么:
for (node <- nodes) {
node.text = node.text.split("-")(0)
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为节点是不可变的.我查看了Node的复制方法,但它不包含text在参数中.