Georg Heiler
Georg Heiler

Reputation: 17676

scala call constructor of case class with all fields except one automatically

I am curious how to call the constructor of a scala case class with all of its fields except one (automatically)

case class MyClass(a:String, b:Int, c:String)
val myThing = MyClass("a", 1, "b")

Something like MyClass("someOtherValue", myThing.getAllTheValuesExceptOne: _*) did not yet work for me.

Upvotes: 1

Views: 1007

Answers (2)

Vod
Vod

Reputation: 106

Another option is to create a companion object with an apply method.

object MyClass {
  def apply(a: String) = {
    new MyClass(a, 1, "AAA")
  }
}

Then you can just use

val newInstance = MyClass("BBB")

Upvotes: 1

vvg
vvg

Reputation: 6385

You can use copy method of case classes, it allows to create case class based on others overriding some particular fields.

case class MyClass(a:String, b:Int, c:String)
val myThing = MyClass("a", 1, "b")
val myThing2 = myThing.copy(a = "someOtherValue")

Upvotes: 8

Related Questions