0

My question is simple.

Why does this code make an error,

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)
                      ^

whereas this code does not?

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 <: A.Inner. Isn't it?

Naetmul
  • 14,544
  • 8
  • 57
  • 81

1 Answers1

2

Here, lower-bound should be used:

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

object A {
  class Inner(a: A)
}

Only if T is ancestor of A.Inner, then A.Inner can be converted to T. We use lower-bound to restrict T is ancestor of A.Inner.

Zang MingJie
  • 5,164
  • 1
  • 14
  • 27