Я пытаюсь реализовать некоторую функцию в суперклассе, поэтому мне не нужно всегда повторять ее в своих дочерних элементах. Образец:
trait Animal {
def applyF(transition: Animal => Animal): Animal = transition(this) // Animal as param and return type
}
case class Cat(color: String) extends Animal {
def changeColor(color: String): Cat = this.copy(color)
def update(): Animal = {
val transition = (cat: Cat) => cat.changeColor("yellow") // Cat as param and return type
applyF(transition) // <-- Type mismatch, expected: Animal => Animal, actual: Cat => Cat
}
}
Но это дает несоответствие типов, потому что Cat
не Animal
. Почему это не работает? Cat расширяет Animal, так что это должно быть животное, верно?
Это как-то связано с ко-/контравариантом?
Как я могу это исправить?
----- Обновлять -----
Второй пример:
trait Animal {
def applyF[A >: this.type <: Animal](transitions: Iterable[A => Animal]): Animal =
transitions.foldLeft(this)((animal, transition) => transition(animal))
}
case class Cat(color: String) extends Animal {
def changeColor(color: String): Cat = this.copy(color)
def update(): Animal = {
val transition = (cat: Cat) => cat.changeColor("yellow") // Cat as param and return type
applyF(Iterable(transition)) // <-- Type mismatch, expected: A, actual: entity.type (with underlying type example.state.Entity)
}
}