找不到具有下限类型边界的方法参数的隐式转换



我有这个代码:

class Action[T]
class Insert[T] extends Action[T]
case class Quoted[T]()
implicit def unquote[T](q: Quoted[T]): T = {
throw new Exception("Success")
}
def test[A <: Action[_]](a: A): A = {
return a
}
try {
test[Insert[String]](Quoted[Insert[String]])
test(unquote(Quoted[Insert[String]]))
// test(Quoted[Insert[String]]) // does not compile
} catch {
case e: Exception => print(e.getMessage())
}

斯卡拉菲德尔

注释行在编译期间失败:

error: inferred type arguments [ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]] do not conform to method test's type parameter bounds [A <: ScalaFiddle.Action[_]]
test(Quoted[Insert[String]])
error: type mismatch;
found   : ScalaFiddle.Quoted[ScalaFiddle.Insert[String]]
required: A
test(Quoted[Insert[String]])

有没有办法在不指定类型参数或像前两行那样显式使用转换函数的情况下使其编译?

也许您可以像这样重载测试方法:

def test[A, B <: Action[_]](a: A)(implicit f: A => B): B = f(a)

然后这确实编译并工作:

test(Quoted[Insert[String]])

不过,我对为什么有必要解释并不积极。也许,如果您没有明确说明类型参数,则在应用任何隐式转换之前,会根据边界对其进行推断和检查。在您的示例中,隐式转换搜索是由类型参数和参数不匹配触发的。

最新更新