mushroom
mushroom

Reputation: 6289

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.

Upvotes: 0

Views: 50

Answers (1)

0__
0__

Reputation: 67330

In principle you cannot. Implicit resolution happens at compile time.

If you can enumerate over SomeTrait, you can of course do something with a pattern match, like

trait SomeTrait[A]
implicit object SomeIntTrait    extends SomeTrait[Int]
implicit object SomeStringTrait extends SomeTrait[String]

def doSomething[A: SomeTrait](a: A) = ???

def atRuntime(x: Any) = x match {
  case i: Int    => doSomething[Int](i)
  case s: String => doSomething[String](s)
}

Upvotes: 1

Related Questions