Scala inherit parameterized constructor

后端 未结 4 980
不知归路
不知归路 2021-02-02 09:53

I have an abstract base class with several optional parameters:

abstract case class Hypothesis(
    requirement: Boolean = false,
    onlyDays:   Seq[Int] = Nil,         


        
4条回答
  •  心在旅途
    2021-02-02 10:53

    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
      }
    }
    

提交回复
热议问题