gpt4 book ai didi

scala - 获取更新的不可变对象(immutable对象)的更短方法?

转载 作者:行者123 更新时间:2023-12-01 10:01:15 26 4
gpt4 key购买 nike

我有一个带有多个参数的类,例如 class Building(val a: Int, val b: Int, val c: Int)。我必须更新的这段代码是这样的:

def updatedA(a: Int): Building = new Building(a, this.b, this.c)
def updatedB(b: Int): Building = new Building(this.a, b, this.c)

有没有更短的方法来获取像下面这样的更新对象?

def updatedA(newA: Int): Building = new { val a = newA } extends this // doesn't compile/ type is AnyRef instead of Building

最佳答案

你有没有看过copyWith() construction mechanism

The copyWith method takes advantage of Scala 2.8's default arguments. For each field in the class, it has a parameter which defaults to the current value. Whichever arguments aren't specified will take on their original values. We can call the method using named arguments (also in Scala 2.8).

val newJoe = joe.copyWith(phone = "555-1234")

或者查看 copy mechanism对于案例类。

/* The real power is the copy constructor that is automatically generated in the case class. I can make a copy with any or all attributes modifed by using the copy constructor and declaring which field to modify */

scala> parent.copy(right = Some(node))

关于scala - 获取更新的不可变对象(immutable对象)的更短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15790235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com