user_1357
user_1357

Reputation: 7940

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)
}

Upvotes: 0

Views: 133

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51703

I'm not sure what you're doing (I asked several questions in comments), but yes, you can get the object from ClassTag

import scala.reflect.ClassTag
import scala.reflect.runtime

def temp[T <: SomeType]()(implicit tag: ClassTag[T]): Option[/*T*/SomeType] = {
  val runtimeMirror = runtime.currentMirror
  val classSymbol = runtimeMirror.classSymbol(tag.runtimeClass)
  val companionSymbol = classSymbol.companion.asModule
  val companionModuleMirror = runtimeMirror.reflectModule(companionSymbol)
  val companionInstance = companionModuleMirror.instance
  companionInstance.asInstanceOf[SomeTrait[T]].get(1)
}

temp[ConcreteType]()

Upvotes: 1

Related Questions