gpt4 book ai didi

Scala 案例类 : avoid recomputation of the property

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

我问这个是因为我多次遇到这个用例。

假设我们有一个这样的案例类:

case class C(xs: Iterable[Int]) {
val max = xs.max

def ++(that: C) = C(xs ++ that.xs)
}

这工作正常,但是 ++ 操作效率低下,因为不必要地再次遍历集合以计算结果的最大值;因为我们已经知道两个集合的最大值,所以我们可以重用它——通过使用类似这样的东西:

def ++(that: C) =
C(xs ++ that.xs, max = math.max(max, that.max))

这只是一个演示目的的简单示例 - 避免的计算可能要复杂得多,甚至可能是 TCP 数据获取。

如何避免这种重新计算(参见第二个代码片段),同时保持代码的优雅?

最佳答案

像这样的东西会起作用

class C private (val xs: Iterable[Int], val max: Int) {        

def ++(that: C) = new C(xs ++ that.xs, math.max(this.max, that.max)
}

object C {
def apply(xs: Iterable[Int]) = new C(xs, xs.max)
}

请注意,C 不再是 case 类,以避免 max 和 xs 变得不一致。如果 C 是案例类,您可以调用例如c.copy(max = -1) 并得到一个不一致的实例。

关于Scala 案例类 : avoid recomputation of the property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014489/

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