Используйте супер метод с подтипом param - PullRequest
0 голосов
/ 25 апреля 2019

Я пытаюсь реализовать какую-то функцию в суперклассе, поэтому мне не всегда нужно повторять ее в дочерних классах. Пример:

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)
  }
}

Ответы [ 2 ]

2 голосов
/ 25 апреля 2019

Cat расширяется Animal, но Cat => Cat не расширяется Animal => Animal.

A => B является ковариантным относительно B и контравариантным относительно A, т.е. еслиA1 <: A, B1 <: B затем A => B1 <: A => B <: A1 => B.

Что если вы параметризуете Animal#applyF?

trait Animal {
  def applyF[A >: this.type <: Animal](transition: A => Animal): Animal = transition(this)
}

trait Animal { 
  def applyF[A >: this.type <: Animal](transitions: Iterable[A => A]): Animal /*A*/ =
    transitions.foldLeft[A](this)((animal, transition) => transition(animal)) 
}
1 голос
/ 25 апреля 2019

Другой вариант - использовать F-ограниченный полиморфизм .

trait Animal[A <: Animal[A]] { self: A =>
  def applyF(transition: Iterable[A => A]): A = // I would use List instead of Iterable.
    transition.foldLeft(this)((animal, transition) => transition(animal))
}
final case class Cat(color: String) extends Animal[Cat] {
  def changeColor(color: String): Cat = this.copy(color)

  def update(): Cat =
    applyF(List(cat => cat.changeColor("yellow")))
}

Однако имейте в виду, что приносит свои проблемы .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...