scalatypeslockingactorf-bounded-polymorphism

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


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]]

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?


Solution

  • 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
    

    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].