1

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.

Georg Heiler
  • 16,916
  • 36
  • 162
  • 292

2 Answers2

8

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")
vvg
  • 6,325
  • 19
  • 36
1

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")
Vod
  • 106
  • 2
  • The question is looking for some `automatic` way. This is way too manual approach specially if you have a lot of fields. – oblivion Jan 25 '17 at 16:55