ferk86
ferk86

Reputation: 2345

shorter way to get an updated immutable object?

I have a class with several parameters such as class Building(val a: Int, val b: Int, val c: Int). This code I have to update it is this:

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

Is there a shorter way to get an updated object like the following?

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

Upvotes: 3

Views: 215

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272257

Have you looked at the 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")

Or check out the copy mechanism for case classes.

/* 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))

Upvotes: 7

Related Questions