Ошибка типа Scala для признаков с циклическими ссылками

У меня проблемы с тем, чтобы этот код работал. Я хочу сделать черту, которая позволяет классу, который наследует его, иметь "детей", но, очевидно, Child"s setParent метод хочет P, но получает Parent[P, C] вместо.

package net.fluffy8x.thsch.entity

import scala.collection.mutable.Set

trait Parent[P, C <: Child[C, P]] {
  protected val children: Set[C]
  def register(c: C) = {
    children += c
    c.setParent(this) // this doesn't compile
  }
}

trait Child[C, P <: Parent[P, C]] {
  protected var parent: P
  def setParent(p: P) = parent = p
}

1 ответ

Решение

Вы должны использовать типы самости, чтобы указать, что this является P и не Parent[P, C], Это также потребует дополнительных границ P <: Parent[P, C] а также C <: Child[C, P]

trait Parent[P <: Parent[P, C], C <: Child[C, P]] { this: P =>
  protected val children: scala.collection.mutable.Set[C]
  def register(c: C) = {
    children += c
    c.setParent(this)
  }
}

trait Child[C <: Child[C, P], P <: Parent[P, C]] { this: C =>
  protected var parent: P
  def setParent(p: P) = parent = p
}
Другие вопросы по тегам