I want to force case subclasses constructors to have a defined creation signature (by using a trait). However, I can't reference a class constructor inside the trait:
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait MyTrait {
def apply[A <: MyTrait](i: Int): A = {
// Neither work:
// new this(i)
// new this.getClass.getMethod("apply")
this(i)
}
def field: Int
def increase(i: Int) = {
this(this.field + i)
}
}
case class MyClass01(field: Int) extends MyTrait {}
// Exiting paste mode, now interpreting.
trait MyTrait
class MyClass01
scala> val mc = MyClass01(0)
val mc: MyClass01 = MyClass01(0)
scala> val mc = MyClass01(0).increase(10)
^
warning: dead code following this construct
(To diagnose errors in synthetic code, try adding `// show` to the end of your input.)
java.lang.StackOverflowError
at MyTrait.apply(<pastie>:6)
at MyTrait.apply$(<pastie>:3)
at MyClass01.apply(<pastie>:17)
⋯
How do I do this in scala?
The idea is to force some case classes
to have a given constructor:
case class MyClass02(field: Int) extends MyTrait {}
case class MyClass03(field: Int) extends MyTrait {}
⋯