Why can we use a new class as type of parent class in Scala?

toa*_*ong 2 types scala locking actor f-bounded-polymorphism

In the simplified implementation of Actor in the RedBook, they use node-based MPSC node based queue for Actor. They define the node by this line of code:

private class Node[A](var a: A = null.asInstanceOf[A]) extends AtomicReference[Node[A]]
Run Code Online (Sandbox Code Playgroud)

But how can we use Node[A] as the type parameter of AtomicReference because we do not have class Node[A] yet? Is it a way of declaring recursive type in Scala?

Mat*_*zok 8

You are allowed to use recursion in class/trait definition:

abstract class Example[A] extends (A => Example[A])

def example(prefix: String): Example[String] = new Example[String] {
  def apply(s: String): Example[String] = {
    val t = prefix + s
    println(t)
    example(t)
  }
}

example("1")("2")("3") 
//12
//123
Run Code Online (Sandbox Code Playgroud)

If you have X extends F[X] then you ended up with something known to C++ developers as curiously recurring template pattern and in type theory in general as F-bounded types.

You can find it even in Java because each enum X is underneath abstract class X extends Enum[X].

  • “ Node [A]”是“ Node [A]”类型,它是“ AtomicReference [Node [A]]”的子类型。“ AtomicReference”本身不是递归的。 (2认同)