Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case classes with inheritance and default parameters

Is there an elegant way in Scala to use case classes (or case classish syntax) with inheritance and default constructor parameters? I kind of want to do this (without repeating the default parameters of the superclass):

abstract class SuperClazz(id: String = "")
case class SubClazz(name: String = "", size: Int = 0) extends SuperClazz
val sub = SubClazz(id = "123", size = 2)
like image 832
reikje Avatar asked Jun 09 '26 17:06

reikje


1 Answers

I would say it's not possible to do without repeating parameters from super class. It is due to the fact that case classes are special type of scala classes. It is beacuse compiler implicitly generates companion extractor object with apply and unapply methods and in those methods it will be no parameter that is not specified in class parameters.

Consider this code snippet

abstract class SuperClazz(id: String = "")
class SubClazz(name: String,id: String) extends SuperClazz {
    override def toString: String = "name: " + name + ",id: " + id
}
object SubClazz {
    def apply(name: String = "", id: String = "") = new SubClazz(name, id)
}

It's shorter and simpler ( and little bit different regarding toString method ) version of what is being created when

case class SubClazz(name: String, id: String) extends SubClazz

is called.

like image 113
goral Avatar answered Jun 12 '26 10:06

goral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!