含糊的隐式转换错误 [英] ambiguous implicit conversion errors

查看:116
本文介绍了含糊的隐式转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个代码片段,试图重现我在实现内部DSL时面临的问题:

Here is a code snippet that tries to reproduce a problem I am facing while implementing an internal 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
}

在显示的位置我得到了模棱两可的隐式转换错误:

I am getting ambiguous implicit conversions errors at the shown locations:

<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
                        ^

但是,注释其中的一个隐式方法并不能解决问题.我正在使用视图边界,因为最后我想链接隐式对象.请注意,上面给出的代码段不涉及隐式链接.

However commenting one of the implicits does not solve the problem. I am using view bounds since finally I want to chain the implicits. Note that the code snippet given above does not involve implicit chaining.

我期望foo1隐式转换将适用于第一个test应用程序,而foo2隐式转换将适用于第二个test应用程序. 我不明白这两个隐式方法如何同时适用于两个test函数应用程序.为什么会发生这种情况,以及如何使其起作用?

I was expecting that foo1 implicit conversion would be applicable for the first test application whereas foo2 implicit conversion would be applicable for the second test application. I don't understand how both the implicits are applicable to both the testfunction applications. Why is this happening and how to make this work?

修改: 如果我不使用视图范围,则如下所示,效果很好.但是我想使用视图边界,因为我想按照隐式链接将隐式链接起来,方法见

Edit: If I don't use view bounds, it works fine as shown below. But I want to use view bounds since I want to chain the implicits the way it is explained in the post 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

推荐答案

恐怕这行不通.解析隐式时只是不考虑视图边界,因此您无法链接隐式.那是设计,因为这样的链接可能会创建一些非常不可读的代码.我看到的唯一选择是为每个可能的转化链创建一个新的隐式转化.

I'm afraid this won't work. View bounds are just not taken into account when resolving implicits and thus you can't chain implicits. That is be design, because such chaining could create some very unreadable code. The only option I see is to create a new implicit conversion for each possible chain of conversions.

这篇关于含糊的隐式转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆