3

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)
1
  • Not possible with regular scala syntax. With macros, this might be possible Commented Apr 7, 2014 at 11:11

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.