tags:

views:

251

answers:

1

Is there a nicer way of doing this?

scala> case class A(x : Int)
defined class A

scala> case class B(override val x : Int, y : Int) extends A(x)
defined class B

I'm extending A with B and adding an extra member variable. It would be nice not to have to write override val before the x.

+6  A: 

I would strongly advise not to inherit from a case class. It has surprising effects on equals and hashCode, and has been deprecated in Scala 2.8.

Instead, define x in a trait or an abstract class.

scala> trait A { val x: Int }
defined trait A

scala> case class B(val x: Int, y: Int) extends A
defined class B

http://www.scala-lang.org/node/3289

http://www.scala-lang.org/node/1582

retronym
On 2.8 I see nothing surprizing regarding equals/hashCode. All required properties of equals are maintained in the most intuitive way. (Instances with runtime type of `case class A` are never equal to instances of `case class B`, regardless if there is inheritance involved).
Dimitris Andreou
To be precise, case classes should not inherit from other case classes. It's OK (and quite common) to let a normal class inherit from a case class.
Martin Odersky
So that means if you write case classes you are effectively sealing those classes. It's a side-effect I wouldn't have expected but I'll be careful of in future.
Dave