代码之家  ›  专栏  ›  技术社区  ›  Alexey Romanov

scala中的自我类型不匹配

  •  3
  • Alexey Romanov  · 技术社区  · 15 年前

    鉴于此:

    abstract class ViewPresenterPair {
      type V <: View 
      type P <: Presenter
    
      trait View {self: V =>
        val presenter: P
      }
    
      trait Presenter {self: P =>
        var view: V
      }
    }
    

    我试图用这种方式定义一个实现:

    case class SensorViewPresenter[T] extends ViewPresenterPair {
      type V = SensorView[T]
      type P = SensorPresenter[T]
    
      trait SensorView[T] extends View {
      }
    
      class SensorViewImpl[T](val presenter: P) extends SensorView[T] {
        presenter.view = this
      }
    
      class SensorPresenter[T] extends Presenter {
        var view: V
      }
    }
    

    这给了我以下错误:

    error: illegal inheritance;
     self-type SensorViewPresenter.this.SensorView[T] does not conform to SensorViewPresenter.this.View's selftype SensorViewPresenter.this.V
             trait SensorView[T] extends View {
                                         ^
    <console>:13: error: type mismatch;
     found   : SensorViewPresenter.this.SensorViewImpl[T]
     required: SensorViewPresenter.this.V
            presenter.view = this
                             ^
    <console>:16: error: illegal inheritance;
     self-type SensorViewPresenter.this.SensorPresenter[T] does not conform to SensorViewPresenter.this.Presenter's selftype SensorViewPresenter.this.P
             class SensorPresenter[T] extends Presenter {
                                              ^
    

    我不明白为什么。毕竟, V 只是一个别名 SensorView[T] 路径是相同的,那么它怎么可能不一致呢?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Alexey Romanov    15 年前

    找到了:当然,参数 T 在一般类型中是不同的。 所以我应该改写

    case class SensorViewPresenter[T] extends ViewPresenterPair {
      type V = SensorView
      type P = SensorPresenter
    
      trait SensorView extends View {
      }
    
      class SensorViewImpl(val presenter: P) extends SensorView {
        presenter.view = this
      }
    
      class SensorPresenter extends Presenter {
        var view: V
      }
    }
    
    推荐文章