Я пытаюсь реализовать какую-то функцию в суперклассе, поэтому мне не всегда нужно повторять ее в дочерних классах. Пример:
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
. Почему это не работает?
Кошка расширяет Животное, поэтому оно должно быть животным, верно?
Это как-то связано с ко / контравариантным?
Как я могу это исправить?
----- Обновление -----
Второй пример:
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)
}
}