简体   繁体   中英

Why does Scala fail to find implicit view when one is available?

Any idea why this fails to find the implicit view?


// Making B invariant fixes it.
sealed trait ImplicitlyStable[A, +B]

object ImplicitlyStable {

  implicit def convertibleToStable[A, B](implicit
                                         aToB: A => B,
                                         // Removing bToB fixes it.
                                         bToB: ImplicitlyStable[B, B]
                                        ): ImplicitlyStable[A, B] = ???
}

object Test {

  def testConvertibleToStable[A, B](implicit
                                    aToB: A => B,
                                    bToB: ImplicitlyStable[B, B]
                                   ): ImplicitlyStable[A, B] =
    implicitly[ImplicitlyStable[A, B]]
}

It fails with:

[error] !I e: ImplicitlyStable[A, B]
[error] ImplicitlyStable.convertibleToStable invalid because
[error] !I aToB: A => B
[error]   No implicit view available from A => B.
[error]
[error]     implicitly[ImplicitlyStable[A, B]]
[error]               ^
[error] one error found

It says No implicit view available from A => B which is clearly not true as there is an implicit parameter of that type.

Is this one of those situations where it is inferring Nothing for B ? If so, why would it do that?


If I add:

  private def unexpected: Nothing = sys.error("Unexpected invocation")
  implicit def nothingStableAmbig1[A]: ImplicitlyStable[Nothing, A] = unexpected
  implicit def nothingStableAmbig2[A]: ImplicitlyStable[Nothing, A] = unexpected
  implicit def nothingStableAmbig3[A]: ImplicitlyStable[A, Nothing] = unexpected
  implicit def nothingStableAmbig4[A]: ImplicitlyStable[A, Nothing] = unexpected

Then it fails with:

[error] ambiguous implicit values:
[error]  both method nothingStableAmbig3 in object ImplicitlyStable of type [A]ImplicitlyStable[A,Nothing]
[error]  and method nothingStableAmbig4 in object ImplicitlyStable of type [A]ImplicitlyStable[A,Nothing]
[error]  match expected type ImplicitlyStable[A,B]
[error]     implicitly[ImplicitlyStable[A, B]]
[error]               ^

So sure enough, it is inferring Nothing , but why?

It seems like this might be a bug in Scala 2 that has been fixed in Scala 3.

I raised an issue for it.

I'm not sure if there is any more reasoning behind why it is inferring Nothing . If anyone knows then that would be great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM