Thiago Pereira Thiago Pereira - 1 year ago 109
Scala Question

Scala: Generic Implicit class

I'm trying to catch the Type from the class I'm implicitly inferring:

case class ToGet(key: String)

class Builder[T <: AnyRef] {

def get(key: String)(implicit mf: Manifest[T]): ToGet = {

object Builder {

import scala.reflect.runtime.universe._

implicit class ToGetImplicits(obj: ToGet) {
def future[T <: AnyRef]()(implicit mf: Manifest[T]): Future[Option[T]] = ???

When I create an instance and call the future above, it returns

Is it possible to get the type here or what should a good way to design that?



val obj = new Builder[String]
obj.get("myKey").future() //this returns a Future[Option[Nothing]]


Added ToGet definition

Answer Source

obj.get("myKey") returns a ToGet. At this point, the manifest was provided and ignored. All we have now is a ToGet.

Now the future call pimped on the ToGet has no type information it can use, so it infers Nothing.

Depending on the intent of the code, you might want to pass the manifest as an implicit parameter to the ToGet class:

case class ToGet [T] (key: String)(implicit val mf: Manifest[T])

And now your implicit class:

implicit class ToGetImplicits[T](obj: ToGet[T]) {
  def future(): Future[Option[T]] = {
    // you can access here for the manifest

The thing is: something has to carry the type information through.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download