Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala inherit parameterized constructor

I have an abstract base class with several optional parameters:

abstract case class Hypothesis(     requirement: Boolean = false,     onlyDays:   Seq[Int] = Nil,     … ) extends Something {…} 

Do i really need to explicitly repeat all parameters with the additional keywords override val on top

case class SomeHypothesis(     anotherArg: SomeType,     override val requirement: Boolean = false,     override val onlyDays:   Seq[Int] = Nil,     … ) extends Hypothesis(     requirement,     onlyDays,     … ) {…} 

Or is there a syntax like

case class SomeHypothesis(anotherArg: SomeType, **) extends Hypothesis(**) {…} 

I don’t even need anotherArg, just a way to pass all keyword args to the super constructor.


I really like Scala’s idea about constructors, but if there isn’t a syntax for that one, I’ll be disappoint :(

like image 881
flying sheep Avatar asked Jun 27 '11 18:06

flying sheep


1 Answers

You can just use a dummy name in the inherited class:

case class SomeHypothesis(anotherArg: SomeType, rq: Boolean = false, odays: Seq[Int] = Nil) extends Hypothesis(rq, odays) 

but you do have to repeat the default values. There is no need to override a val.

EDIT:

Note that your abstract class should not be a case class. Extending case classes is now deprecated. You should use an extractor for you abstract class instead:

abstract class SomeHypothesis(val request: Boolean)  object SomeHypothesis {   def unapply(o: Any): Option[Boolean] = o match {     case sh: SomeHypothesis => Some(sh.request)     case _ => None   } } 
like image 89
axel22 Avatar answered Sep 19 '22 00:09

axel22