neutropolis
neutropolis

Reputation: 1894

Finding an implicit from a type instance

Is it possible to use a Type instance as a normal Scala type? For example, in the following snippet, can one find pi by using tpe?

import scala.reflect.runtime.universe._

implicit val pi: Double = 3.14159265
val tpe = typeOf[Double]
implicitly[Double] // pi
implicitly[tpe]???

I'm afraid that there isn't an easy solution to achieve my goal, and that I am going to need a kind of factory to translate tpe into implicitly[Double]. Anyway, I think that integrating reflection types in Scala code could be really powerful, and so, not as crazy as it could seem.

Upvotes: 1

Views: 419

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

I don't see how this would make much sense.

Let's just talk of what it sould mean for implicitly. It's supposed to fail to compile if there is no such implicit, or more than one eligeable. But because the actual type represented by tpe is not known until runtime, making implicitly work with a type instance would make it impossible to emit any kind of compile error. The best you could do is to arrange for any call to implicitly to always compile, have the compiler store somewhere a list of all the implicit values in scope (for any type), and at runtime lookup in this list and throw an exception if none matches the type represented by tpe (or if there are several). This could only make some kind of sense if we are talking about an alternate implementation of implicitly, say dynamicImplicitly.

Note that this would require the explicit support from the compiler (to capture all the implicits in scope at each call to dynamicImplicitly, which would thus not be a mere simple function), and be very inefficient in terms of space (how many implicits can be in scope at one given point? Yes, a lot, and they would all need to be referenced somehow in the bytecode at each call to dynamicImplicitly).

So my short answer is: don't hold your breath for this feature to be implemented anytime soon. Technically it might be possible to implement dynamicImplicitly as a scala macro (provided that it is possible to get all the implicits in scope from scala macros, which I'm not even sure)

Upvotes: 1

Related Questions