user3612643
user3612643

Reputation: 5772

Get typeOf[this.type] in subclass

How can one let a superclass have access to its concrete instance's type?

class Base {
  val t = typeOf[this.type]
}

class X extends Base {
}

assert((new X).t =:= typeOf[X]) <-- fails!!!

So, the idea is that Base.t should reflect the concrete type of the instance...

Upvotes: 2

Views: 1905

Answers (2)

Mahdi
Mahdi

Reputation: 1852

How about making t a method and making that generic.

  import scala.reflect.runtime.universe._
  class Base {
    def myActualType[T <: Base](b: T)(implicit tt: TypeTag[T]) = typeOf[T]
  }
  class Foo extends Base 
  class Bar extends Foo 
  val bar = new Bar
  assert(bar.myActualType(bar) =:= typeOf[Bar])

The downside is that you always have to send the object reference to it when you call it, but you get what you want.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170745

It's unfortunately a common misunderstanding of this.type: it isn't the class of the instance, it's the singleton type (i.e. the type which only has one member: this). It won't work without inheritance either.

This can be done using F-bounded polymorphism:

class Base[A <: Base[A] : TypeTag] {
  val t = typeOf[A]
}

class X extends Base[X]

Upvotes: 2

Related Questions