有没有办法控制默认使用哪个隐式转换? [英] Is there a way to control which implicit conversion will be the default used?

查看:28
本文介绍了有没有办法控制默认使用哪个隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个:

class String2(val x:String) {def *(times:Int) : String = {val builder = new StringBuilder()for( i <- 0 直到次数) {builder.append(x)}builder.toString()}}

现在如果我添加这个隐式:

implicit def gimmeString2(y:String) = new String2(y)

我会得到一个编译错误,因为 stringWrapper 也添加了这个隐式.有没有办法告诉编译器忽略其他隐式,使用它",这样我就不必实例化 String2 对象并处理它?<​​/p>

我承认示例代码可能不是最合适的(对于这个问题),但我认为它可以.

解决方案

Scala 2.8 为隐式添加了优先级系统.在这个 新 Java 阵列上的 SIP:

<块引用>

当比较重载方法或隐式方法的两种不同的适用替代方案时,每个方法都会因具有更具体的参数而获得一分,并因在适当的子类中定义而获得另一分.如果在这两次比较中获得更多分数,则替代方案胜过"另一个方案

结论 如果替代方案具有相同的参数类型,则在子类中定义的参数类型赢.因此,我相信您可以按如下方式声明隐式:

trait LowPriorityImplicits {//低优先级转换}对象 HighPriorityImplicits 扩展了 LowPriorityImplicits {//这里是高阶的}

Suppose I have this:

class String2(val x:String) {
    def *(times:Int) : String = {
        val builder = new StringBuilder()
        for( i <- 0 until times) {
            builder.append(x)
        }
        builder.toString()
    }
}

now if I add this implicit:

implicit def gimmeString2(y:String) = new String2(y)

I will get a compilation error because stringWrapper also adds this implicit. Is there a way of saying to the compiler "ignore other implicits, use this", so that I don't have to instantiate a String2 object and work on that?

I admit the example code may not be the most appropriate ( for this question ), but I think it will do.

解决方案

Scala 2.8 added a prioritization system for implicits. It's explained in this SIP on the new Java arrays:

When comparing two different applicable alternatives of an overloaded method or of an implicit, each method gets one point for having more specific arguments, and another point for being defined in a proper subclass. An alternative "wins" over another if it gets a greater number of points in these two comparisons

concluding that if alternatives have identical argument types, the one which is defined in a subclass wins. Hence I believe that you could declare implicits as follows:

trait LowPriorityImplicits {
  //lower priority conversions
}

object HighPriorityImplicits extends LowPriorityImplicits {
  //higher-order ones here
}

这篇关于有没有办法控制默认使用哪个隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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