St.Antario
St.Antario

Reputation: 27385

Get ClassTag implicitly for abstract type

I'm trying to get ClassTag implicitly. I have the following trait:

trait Tst{ self =>
  type T
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) = ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst {
  override type T = String
}

Is there a way to get ClassTag by the type variable declaration implicitly without specifying it explicitly?

The thing is I'm trying to make the code as easy to use for clients as possible.

Upvotes: 2

Views: 510

Answers (1)

Mikaël Mayer
Mikaël Mayer

Reputation: 10701

I suggest you use abstract classes, implicit parameters and generics instead of parametric types:

abstract class Tst[T](implicit ev: ClassTag[T]) { self =>
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) = 
    ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst[String]

Note that although Dotty supports traits with parameters, it does not mix as well with generics.

Upvotes: 2

Related Questions