Thiago Pereira Thiago Pereira - 2 months ago 23
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 = {
ToGet(key)
}
}

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
Future[Option[Nothing]]
.

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

EDIT

e.g:

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


EDIT 2

Added ToGet definition

Answer

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 obj.mf here for the manifest
    ???
  }
}

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