Scala: how to refer to the type of an expanding class in a superclass?

Is there a way to define a type Tin Parent in such a way that it Talways becomes the actual type of an expanding class (in this case Child)?

In ParentI want to force / declare to Talways be an extensible type, as if I wrote type T="type_of_the_extending_class"in every valid extending class, without actually writing the lines type T=Child1to Child1, etc.

Thus, the Child1 method should accept Child1 objects as a parameter, and the Child2 method should only accept Child2 objects. Is there an easier way to provide this? Is there a way without recording type T=ChildXin each class ChildX? Is there any way without this template?

I searched for a solution in Scala books, but could not find.

abstract class Parent{
  type T<:Parent
  def method(t:T) 
}

class Child1 extends Parent{
  type T=Child1
  override def method(t:T)=t.child1method
  def child1method=println("child1 method")
}

class Child2 extends Parent{
  type T=Child2
  override def method(t:T)=t.child2method
  def child2method=println("child2 method")
}
+3
1

- F- ( Scala - - Java ..):

trait Parent[T <: Parent[T]] {
  def method(t: T)
}

class Child1 extends Parent[Child1] {
  def method(t: Child1) = println("child1 method")
}

class Child2 extends Parent[Child2] {
  def method(t: Child2) = println("child1 method")
}

F- Scala - Kris Nuttycombe, , , " " , , Scala. , , .

this.type ( ) , , - :

scala> abstract class Parent {
     |   def method(t: this.type)
     | }
defined class Parent


scala> class Child1 extends Parent {
     |   def method(t: this.type) = println("child1 method")
     | }
defined class Child1

scala> val a = new Child1
a: Child1 = Child1@19517e9a

scala> val b = new Child1
b: Child1 = Child1@5737e545

scala> a.method(b)
<console>:12: error: type mismatch;
 found   : b.type (with underlying type Child1)
 required: a.type
              a.method(b)
                       ^

, a.method, a.

+6

All Articles