Scala: How can I make my immutable classes easier to subclass?

前端 未结 1 1346
情深已故
情深已故 2021-02-05 14:12

I\'ve recently created an immutable class supporting operations like +, -, etc. that returns a new instance of that class when it is changed.

I wanted to make a subclass

1条回答
  •  失恋的感觉
    2021-02-05 14:45

    You could use an implementation trait, like the collection classes do, which is parametrized by the concrete type. E.g., something like:

    trait FooLike[+A] {
      protected def bar: Int
    
      protected def copy(newBar: Int): A
      def +(other: Foo): A = copy(bar + other.bar)
    }
    
    class Foo(val bar: Int) extends FooLike[Foo] {
      protected def copy(newBar: Int): Foo = new Foo(newBar)
    }
    
    class Subclass(barbar: Int) extends Foo(barbar) with FooLike[Subclass] {
      protected def copy(newBar: Int): Subclass = new Subclass(newBar)
    }
    

    0 讨论(0)
提交回复
热议问题