Search code examples
scalaabstract-type

Scala Abstract Type Member


I noticed that I can instantiate a scala trait with an abstract type member. The code below compiles. But what is the t.B?

trait A {
    type B
}

val t = new A {}

Solution

  • The type is t.B.

    trait A {
      type B
      def f(b: B)
    }
    
    val t = new A { def f(b: B) = {} }
    
    t.f(0)
    

    has the error

    error: type mismatch;
    found   : Int(0)
    required: t.B
    

    Types don't have to be "overriden" like methods.

    This type is its own thing. It's not very useful, but that's what it is.

    Like all other types, it is a subtype of Any and a supertype of Nothing.

    Seq[t.B](): Seq[Any]
    Seq[Nothing](): Seq[t.b]
    

    And that's about all that can be said about it.