synapse synapse - 3 months ago 10
Scala Question

Nothing inferred for type parameter

How is it possible that type parameter in call to

get[A]
is
Nothing
in this snippet? What can I do to force a compiler to produce an error when
get
is called without explicit type parameter?

case class User(email: String)

object Hello {
def main(args: Array[String]): Unit = {
val store = new ObjectStore
store.get
}
}

class ObjectStore {
def get[A: Manifest]: Option[A] = {
println(manifest[A].toString())
None
}
}

Answer

Based on this blog post, the following should work:

@implicitNotFound("Nothing was inferred")
sealed trait NotNothing[-T]
object NotNothing {
  implicit object notNothing extends NotNothing[Any]
  implicit object `\n The error is because the type parameter was resolved to Nothing` extends NotNothing[Nothing]
}

class ObjectStore {
  def get[T](implicit evManifest: Manifest[T], evNotNothing: NotNothing[T]): Option[T] = {
    println(manifest[T].toString())
    None
  }
}

object X {
  val oo = new ObjectStore().get[Any]
  //fails to compile
  //val o = new ObjectStore().get
}