【问题标题】:Type mismatch: the type referenced in object not the same as the one defined in a trait that object extends?类型不匹配:对象中引用的类型与对象扩展的特征中定义的类型不同?
【发布时间】:2013-02-23 20:23:41
【问题描述】:

对象O 扩展了一个特征T1,它定义了C 类型。

在T1 中,我想操作对象O 中定义的静态数据结构stack。 但是编译器一直在抱怨

找到 T1.this.C 的类型不匹配,需要 O.C

代码如下:

trait T1 {

 case class C(i: Int, s: String)
  def dumbAdd(i: Int, s: String) = {
    O.stack.push(C(i, s))  // type mismatch error goes here.
  }
}

object O extends T1 {

  var stack: Stack[C] = new Stack[C]

}

我很困惑...O 不知道C 并且应该与T1 中的类型相同? 我在这里想念什么? 我该怎么做?

更新

基于将C 放入对象T1 的一项建议,但在我的实际示例中,对象T1 无法访问特征T1 中定义的类型。减少的问题如下:

trait T1 {

  abstract sealed class S

  case class SC extends S

  def dumbAdd(i: Int, s: String) = {
    O.stack.push(C(i, s))
  }
}

object T1 {

  case class C(i: Int, s: String)

  def tryASC {
    val scc = SC() // Here the compiler says not found value SC
  }
}

object O extends T1 {

  var stack: Stack[C] = new Stack[C]

}

【问题讨论】:

  • 请添加错误消息的行和插入符号,以便我们确切地知道在哪里发现了不匹配。
  • @DanielC.Sobral 我更新了帖子。谢谢!

标签: scala


【解决方案1】:

嵌套类属于其父类的一个实例。也就是下面x和y的类型不同:

val a = new T1 {}
val b = new T2 {}
val x = new a.C(0, "")
val y = new b.C(0, "")

x 的类型实际上是a.C,y 的类型是b.C。

您的代码中的问题是您在引用 C 时没有指定 C 所属的实例是什么,最终结果是它们都被假定来自不同的实例。

嵌套类很有用,但由于其非常严格的语义而难以使用。

【讨论】:

  • 路径相关类型。一种解决方案:将 C 放入 object T1。
  • @pedrofurla 是的。但似乎对象 T1 无法访问 trait T1 中定义的类型(类)......
  • 你的例子中没有定义类型。
  • @pedrofurla 对不起.. s 是一个错字。我尝试在我的真实代码示例中使用您的技术,但我发现无法在伴随对象中访问 trait 中定义的类型。
  • 再次阅读我的评论。您不需要在 trait 中访问它,因为它将在对象中。
猜你喜欢
  • 2016-11-07
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 2021-10-10
  • 2018-05-25
相关资源
最近更新 更多