FAQ Database Discussion Community


Getting at runtime class information when you cannot specify ClassTag

scala,scala-reflect
When writing tests to verify that the proper typeclass is selected somewhere in the internals, I've run into type erasure. I don't have the option of adding ClassTag to the signature, unless I also pollute the non-test version of the trait because adding : ClassTag changes the method signature so...

How to instantiate a Scala object using reflection

scala,reflection,scala-2.10,scala-2.11,scala-reflect
I have some code that uses reflection to instantiate a Java or Scala class, allowing a user to specify the name: Assume that loadIt below is a hypothetical method defined using this approach. def getInstance(name:String, jar:String) = { val c:Class[_] = loadIt(name, jar) // load class from the jar c.newInstance.asInstanceOf[AnyRef]...

Why do we have to explicitly specify the ClassTag typeclass

scala,typeclass,scala-reflect
Now that scala has iterated towards a JVM type erasure fix with the ClassTag typeclass, why is it an opt-in, rather than having the compiler always capture the type signature for runtime inspection. Having it an implicit parametrized type constraint would make it possible to call classTag[T] regardless of the...

Scala macros referring to a member type

scala,scala-macros,scala-2.11,scala-reflect
I have a trait with a member type, and want to have a macro with signature containing this type: trait Foo { class Bar[A] { ... } def baz[A](x: Bar[A]): Bar[A] = macro bazImpl[A] def bazImpl[A: c.WeakTypeTag](c: blackbox.Context)(x: c.Expr[Bar[A]]) = ... } This doesn't work, since bazImpl must belong either...

Why is reflect.runtime.universe.RuntimeClass inferred over Nothing when reflect.runtime.universe._ is present?

scala,scala-reflect
I've stumbled upon a strange situation where having reflect.runtime.universe._ imported causes reflect.runtime.universe.RuntimeClass to be inferred where it seems Nothing would be more appropriate. Consider this simple method and List: import scala.reflect.ClassTag def find[A : ClassTag](l: List[Any]): Option[A] = l collectFirst { case a: A => a } val list =...

Dynamically Load an Actor if it's there

scala,akka,scala-reflect
I have the following code lazy val restEndpoint = context.actorOf(Props[RestEndpoint], "RestEndpoint") However, I want to dynamically load the actor if it's there for a few reasons: It may not be on the classpath, so I would have to ask the class loader if it's there. Even if it's on the...