1

我有这个代码:

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]])

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

4

1 回答 1

2

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

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

然后这确实编译和工作:

test(Quoted[Insert[String]])

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

于 2017-07-05T22:00:47.487 回答