Scala inherit parameterized constructor

后端 未结 4 974
不知归路
不知归路 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:39

    In my mind the policy of default values doesn't belong in the base class but should go on the concrete classes. I'd instead do the following:

    trait Hypothesis {
      def requirement: Boolean
      def onlyDays: Seq[Int]
      /* other common attributes as necessary */
    }
    
    case class SomeHypothesis(anotherArg: SomeType,
                              requirement: Boolean = false,
                              onlyDays: Seq[Int] = Nil)
      extends Hypothesis
    

    The case class fields of SomeHypothesis will fulfill the requirements of the Hypothesis trait.

    As others have said, you can still use an extractor for pattern matching on the common parts:

    object Hypothesis {
      def unapply(h: Hypothesis): (Boolean, Seq[Int]) = (h.requirement, h.onlyDays)
    }
    

提交回复
热议问题