问题
The following code does not compile on Scala 2.12 / 2.13. Why?
class X[U, T]
object X {
implicit def genericX[U, T](implicit ev: T <:< U): X[U, T] = new X[U, T]
}
implicitly[X[AnyRef, String]] // compiles
implicitly[X[String, Nothing]] // does not compile
回答1:
Long story short, compiler doesn't like to infer Nothing
in implicits.
Why doesn't Scala's implicit class work when one of the type parameters should be Nothing?
Implicit error when trying to implement the `Absurd` typeclass
https://www.reddit.com/r/scala/comments/73791p/nothings_twin_brother_the_better_one/
http://guillaume.martres.me/talks/typelevel-summit-oslo/?fbclid=IwAR1yDSz-MetOgBh0uWMeuBuuL6wlD79fN_4NrxAtl3c46JB0fYCYeeGgp1Y#/9 (slide 10 "The fear of Nothing
")
https://www.youtube.com/watch?v=YIQjfCKDR5A?t=459 (7:39)
https://www.youtube.com/watch?v=lMvOykNQ4zs
The fear of
Nothing
scalac
instantiates eagerly, even when it isn't safeCounterbalanced by never inferring
Nothing
class Foo[T] { def put(x: T) = {} } (new Foo).put("") // T? = String
Fails if the lower bound isn't
Nothing
class Foo[T >: Null] { def put(x: T) = {} } (new Foo).put("") // T? = Null // type mismatch: Null does not match String
Sometimes you really want to infer
Nothing
!class Foo[T] def foo[T](x: Foo[T]) = x foo(new Foo[Nothing]) // error
Workaround is to introduce type Bottom
type Bottom <: Nothing
implicitly[Bottom =:= Nothing]
implicitly[Nothing =:= Bottom]
implicitly[X[AnyRef, String]] // compiles
// implicitly[X[String, Nothing]] // does not compile
implicitly[X[String, Bottom]] // compiles
来源:https://stackoverflow.com/questions/61951621/failed-implicit-resolution-for-nothing-with