2013-04-03 55 views
3

我有一個類有幾個參數,如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 
+0

如何那第二個想法會比第一個想法更短或更直接? – Jesper

回答

7

你看過copyWith()construction mechanism

copyWith方法利用了Scala 2.8的默認參數。 對於該類中的每個字段,它都有一個參數,該參數默認爲 當前值。無論哪個參數未被指定,都將採用其原始值 。我們可以使用命名參數調用該方法(同樣在 Scala 2.8中)。

VAL newJoe = joe.copyWith(電話= 「555-1234」)

或檢查出copy mechanism爲case類。

/*實際功耗是複製構造函數,它自動在case類中生成 。我可以在任何副本或全部 屬性使用拷貝構造函數,並宣佈其 字段可修改*/

斯卡拉體改> parent.copy(右=一些(節點))

+0

太棒了。使用像_這樣的簡寫符號使我忘記了可以切換參數的順序,並使用(paramName = paramValue)符號來傳遞它們。 – ferk86

相關問題