考慮到在創建時計算了默認欄位的案例類,是否可以將其復制到新復制的案例類重新計算該欄位的地方?
例如,TestCopy.auto在創建時生成:
case class TestCopy(static: String, auto: Long = System.currentTimeMillis()) {
val auto2 = System.currentTimeMillis()
}
如果我復制它只更改欄位static:
val a = TestCopy(static = "a")
val b = a.copy(static = "b")
auto不會重新計算該欄位。建構式欄位也不是auto2:
> println(a)
> println(b)
> println(a.auto2)
> println(b.auto2)
TestCopy(a,1640773176392)
TestCopy(b,1640773176392)
1640773176392
1640773176392
實際上,這是有道理的,因為我正在復制案例類。但是,我想要一種類似于重新創建案例類的行為,我只更改一組靜態欄位。上面的例子是簡化的,我可以重新創建它。問題針對以下情況:
case class TestCopy2(static1: String,
static2: String,
static3: String,
auto: Long = System.currentTimeMillis())
只有在static1必須改變,static2而且static3必須被復制,并且auto必須重新生成。是否可以?
謝謝你們。
uj5u.com熱心網友回復:
自定義apply方法是可行的,但您也應該能夠利用該abstract case class技巧:
abstract case class TestCopy(static: String, auto: Long = System.currentTimeMillis()) {
def copy(static: String = static, auto: Long = System.currentTimeMillis()): TestCopy =
new TestCopy(static, auto)
}
object TestCopy {
def apply(static: String, auto: Long = System.currentTimeMillis()): TestCopy =
new TestCopy(static, auto)
}
使得case class abstract抑制自動生成apply和copy方法。在這種情況下,自動生成apply的基本上就是編譯器會生成的。生成的copy通常是這樣的
def copy(static: String = static, auto: Long = auto): TestCopy
請注意,auto默認為前一個值,因此這是我們想要更改的行為,因此我們定義了一個自定義copy方法來替換編譯器生成的方法。
auto可以通過將建構式設為私有來消除默認值之一;因為case classes 通常不會用 實體化new,所以這沒什么損失:
abstract case class TestCopy private (static: String, auto: Long) {
def copy(static: String = static, auto: Long = System.currentTimeMillis()): TestCopy =
new TestCopy(static, auto)
}
object TestCopy {
def apply(static: String, auto: Long = System.currentTimeMillis()): TestCopy =
new TestCopy(static, auto)
}
現在你可以:
- 使用默認當前時間創建:
TestCopy("foo") - 使用預設時間創建:
TestCopy("foo", 0) - 復制當前時間:
TestCopy("foo").copy(static = "bar") - 預設時間復制:
TestCopy("foo").copy(auto = 0)
uj5u.com熱心網友回復:
瞬態值不會自動復制:
case class Foo(a: Int) {
@transient val b: Long = System.currentTimeMillis
}
val f1 = Foo(1)
Thread.sleep(1000)
val f2 = f1.copy(2)
assert f1.b != f2.b
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403451.html
標籤:
