Self-Service Overview

I searched a bit, but I could not find an example of such a structure:

Person[P <: Person[P]]

which is explained as I understand it.

How to solve this? This seems like endless recursion to me, but it seems like I'm wrong in this conclusion.

+5
source share
2 answers

The structure itself is explained on Twitter by Scala School and is called F-limited polymorphism.

// you define it like this
trait X extends Person[X]

// it then gets expanded to this
trait Person[X extends Person[X]]

This structure is used when the trait must have a reference to the type of object that it extends. If Scala’s explanation is not enough, you can search the Internet for “F-limited polymorphism”

+5
source

- ( Scala -), , , , , , .

. , Animal breed, Animal Animal.

trait Animal {
  def breed(a: Animal): Animal
}

, , , - breed, , , .

class Cow extends Animal {
  def breed(c: Cow) = new Cow
}

, breed . , , .

:

trait Animal[A <: Animal[A]] {
  def breed(a: A): A
}

class Cow extends Animal[Cow] {
  def breed(c: Cow) = new Cow
}

EECOLOR, F- .

+5

All Articles