Scala inherit parameterized constructor

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

    I've spend DAYS bashing my head on the desk trying to understand why named params were not going into an extended class.

    I tried traits, copy() you name it - me and the compiler were always at odds and when things did compile the values never got passed.

    So to be clear if you have class

    class A(someInt:Int = 0, someString: String ="xyz", someOtherString: String = "zyx")  
    

    And you want to extend it:

    class B extends A // does NOT compile 
    
    class B(someInt: Int, someString: String, someOtherString: String) extends A // compiles but does not work as expected 
    

    You would think that a call to B like so:

    case object X = B(someInt=4, someString="Boo", someOtherString="Who") 
    

    Would in fact either NOT compile (sadly it does) or actually work (it does NOT)

    Instead you need to create B as follows (yes this is a repeat of an above answer but it wasn't obvious at first when google led me here...)

    class B(someInt: Int, someString: String, someOtherString: String) extends A(someInt, someString, someOtherString) 
    

    and now

    case object X = B(someInt=4, someString="Boo", someOtherString="Who") 
    

    Both COMPILES and WORKS

    I have not yet worked out all the combinations and permutations of what/when and where you can put default values in the class B constructor but I'm pretty sure that defaults can be specified in the definition of class B with "expected" results.

提交回复
热议问题