Scala: implementing method with return type of concrete instance

前端 未结 4 572
北恋
北恋 2021-01-30 07:23

I need a way to enforce a method in an abstract class to have a return type of the concrete class of the object it is called on. The most common example is a copy

4条回答
  •  独厮守ぢ
    2021-01-30 07:49

    Do not force the type bound on the declaration side, unless you need that bound within the definition of A itelf. The following is sufficient:

    abstract class A(id: Int) {
      type Self
      def copy(newId: Int): Self
    }
    

    Now force the Self type on the use site:

    def genNewId(): Int = ???
    def createCopies[A1 <: A { type Self = A1 }](seq: Seq[A1]): Seq[A1] = 
      seq.map(_.copy(genNewId()))
    

提交回复
热议问题