dimanche 25 octobre 2020

Construct Scala Object (Singleton) from ClassTag

Is it possible to do something like below? We have a ConcreteType which has trait definition and Object definition. At runtime I want to create Object version to access get method of some ConcreteType. Note code below throws cannot cast to SomeTrait exception at asInstanceOf. Also I am using some library that uses format below so have no choice but to work with this construct.

trait SomeType

trait SomeTrait[T <: SomeType] {
  def get(i: Int): Option[SomeType]
}

trait ConcreteType extends SomeType

object ConcreteType extends SomeTrait[ConcreteType]
   
def temp[T <: SomeType]()(implicit tag: ClassTag[T]): Option[T] = {
   asInstanceOf[SomeTrait[T]].get(1)
}




Aucun commentaire:

Enregistrer un commentaire