如果有Foobar[A, B](x: A)
的证据,我有一个班级Foobar(x) => x
和一个隐式转换方法来转A <:< B
。这当前有效,所以如果我调用Foobar(x).xyzzy
,其中xyzzy
是在x上定义的方法,只要证据表明A <:< B
转换正常。我的问题是,如果没有A <:< B
存在的证据,请使用Foobar(x).xyzzy
不是xyzzy
成员的消息调用Foobar
错误。这是事实,我理解为什么会发生这种情况,但我希望在这种情况下的错误代替Cannot prove A <:< B
或其他事情。我认为implicitNotFound
可以帮助我做到这一点,但我却无法使其发挥作用。
示例:
import scala.language.implicitConversions
class Qwerty[A](val _value: A) {
def toFoobar[B](func: A => B): Foobar[A,B] = new Foobar[A,B](_value, func)
}
object Qwerty {
implicit def wrapQwerty[A](anything: A): Qwerty[A] = new Qwerty(anything)
implicit def unwrapQwerty[A](qwerty: Qwerty[A]): A = qwerty._value
implicit def unwrapFoobar[A, B >: A](foobar: Foobar[A, B]): B = foobar.func(foobar._value)
}
class Foobar[A, B](val _value: A, val func: A => B) { }
import Qwerty._
println(5.toFoobar(_ + 2) - 1) // works
println(5.toFoobar(_ + "bad type") - 1) // errors (correctly) but I want error message to say "type mismatch"