简体   繁体   中英

Type mismatch: the type referenced in object not the same as the one defined in a trait that object extends?

Object O extends a trait T1 which has the type C defined.

In T1 I want to manipulate the static data structure stack defined in object O . but the compiler keeps on complaining

type mismatch that found T1.this.C, require OC

The code is like:

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]

}

I am confused... doesn't O know C and should be the same type as the one in T1 ? What am I missing here? and how can I do what I want?

Update

Based on one suggestion to put C in object T1 , but in my real example, the object T1 can't access to the types defined in trait T1 . The reduced problem is as below:

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]

}

Nested classes belong to an instance of their parent class. That is, the types of x and y below are different:

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

The type of x is, literally, aC , and the type of y is bC .

The problem in your code is that you are referring to C without specifying what's the instance to which that C belongs to, with the end result being that they are all assumed to be from different instances.

Nested classes are useful, but difficult to use due to their very strict semantics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM