【发布时间】:2012-07-29 05:47:08
【问题描述】:
这是一个代码 sn-p,它试图重现我在实现内部 DSL 时遇到的问题:
object testObj {
implicit def foo1[T <% Function1[Int, Int]](fun: T): String = "foo1"
implicit def foo2[T <% Function2[Int, Int, Int]](fun: T): String = "foo2"
def test(arg: String): Unit = {}
test((x:Int) => 5) //Ambiguous implicit conversion error
test((x:Int, y:Int) => 5) //Ambiguous implicit conversion error
}
我在显示的位置收到不明确的隐式转换错误:
<console>:21: error: type mismatch;
found : Int => Int
required: String
Note that implicit conversions are not applicable because they are ambiguous:
both method foo1 in object testObj of type [T](fun: T)(implicit evidence$1: T => (Int => Int))String
and method foo2 in object testObj of type [T](fun: T)(implicit evidence$2: T => ((Int, Int) => Int))String
are possible conversion functions from Int => Int to String
test((x:Int) => 5) //Ambiguous implicit conversion error
^
但是,评论其中一个隐式并不能解决问题。我正在使用视图边界,因为最后我想链接隐式。请注意,上面给出的代码 sn-p 不涉及隐式链接。
我期望foo1 隐式转换适用于第一个test 应用程序,而foo2 隐式转换将适用于第二个test 应用程序。
我不明白这两个隐式如何适用于 testfunction 应用程序。为什么会发生这种情况以及如何使其发挥作用?
编辑: 如果我不使用视图边界,它可以正常工作,如下所示。但我想使用视图边界,因为我想按照How can I chain implicits in Scala? 帖子中解释的方式链接隐式。
implicit def foo1(fun: Function1[Int, Int]): String = "foo1"
implicit def foo2(fun: Function2[Int, Int, Int]): String = "foo2"
def test(arg: String): Unit = {}
test((x:Int) => 5) //No error
test((x:Int, y:Int) => 5) //No error
【问题讨论】:
-
我不明白你想要达到什么目的。您能否详细说明如何以显式方式解释代码?
-
我知道很难理解代码在做什么...我已经简化了太多以使其无用...但是完整的代码涉及太多的依赖项,我觉得很难在这里提一下。我已经编辑了帖子以包含一个没有视图边界的示例,该示例有效。但我想使用视图边界的原因是按照编辑的解释链接隐式。
-
你想链接什么?你想同时调用两个隐式吗?当您使用函数调用
test时,输出应该是什么(或者更好的是应该调用哪个隐式)? -
@sschaef 对于第一个
test调用,foo1应该被调用,对于第二个test调用,foo2应该被调用。 (如果我不使用视图边界,这可以正常工作。) -
是的,但这并不能解释您要为视图绑定填写的内容。如果您将隐式显式称为
test(foo1((x:Int)=>5)(???)),???应该是什么?