【问题标题】:Scala: Type matching of a type alias with upper boundScala:类型别名与上限的类型匹配
【发布时间】:2016-05-04 05:51:57
【问题描述】:

我的问题很简单。

为什么这段代码会出错,

abstract class A {
  type T <: A.Inner
  def toT: T = new A.Inner(this)
}

object A {
  class Inner(a: A)
}

// Exiting paste mode, now interpreting.

<console>:16: error: type mismatch;
 found   : A.Inner
 required: A.this.T
         def toT: T = new A.Inner(this)
                      ^

而这段代码没有?

abstract class A {
  type T = A.Inner
  def toT: T = new A.Inner(this)
}

object A {
  class Inner(a: A)
}

// Exiting paste mode, now interpreting.

defined class A
defined object A

A.Inner &lt;: A.Inner。不是吗?

【问题讨论】:

    标签: scala typing type-alias upperbound


    【解决方案1】:

    这里应该使用下限:

    abstract class A {
      type T >: A.Inner
      def toT: T = new A.Inner(this)
    }
    
    object A {
      class Inner(a: A)
    }
    

    仅当TA.Inner 的祖先时,A.Inner 才能转换为T。我们使用下界来限制TA.Inner 的祖先。

    【讨论】:

      猜你喜欢
      • 2010-12-21
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 2013-12-21
      相关资源
      最近更新 更多