Method inheritance in immutable classes

五迷三道 提交于 2019-12-05 18:10:12

I've answered a similar question before and the comment by @GaborBakos is spot on. If you'd like to be able to do similar things to what you might find with the map method of TraverseableLike then you need to do the following:

trait MyTrait[T <: MyTrait[T]]{
  def update(newValue: Int): T
}

which basically is a type definition which depends on itself! Hence, the return type of update is T. Then:

class MyClass(value: Int) extends MyTrait[MyClass]{
  def update(newValue: Int) = new MyClass(newValue)
}

which should work since T is MyClass.

Side Note:

Don't put val in a trait. Instead, make it a def. That way, you don't run into initialization ordering issues with anyone that wants to extend your class. If you don't follow this advice, then you can run into situations where a very NOT null field is being treated as a null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!