samedi 19 septembre 2015

Call method with implicit argument where type is only known at runtime

Say I have a method like this:

def doSomething(a : A)(implicit someTrait : SomeTrait[A]) : B = { ... }

I call a Java method that gives me an AnyRef back and I want to pass the returned object to doSomething:

val obj : AnyRef = javaObject.getRef
doSomething(obj)

I have enough information at runtime to get a more specific type T for the AnyRef object. I am certain that there will be SomeTrait[T] for whatever type T I find at runtime.

How can I call doSomething on the AnyRef? Can I look up the SomeTrait[T] at runtime somehow and pass it explicitly?

I do not care if this potentially blows up at runtime.





Aucun commentaire:

Enregistrer un commentaire