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

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

问题描述

假设我有这个:

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)

我会得到一个编译错误,因为stringWrapper也添加了这个隐式.有没有一种对编译器说忽略其他隐式函数,使用它"的方法,这样我就不必实例化String2对象并对其进行处理?

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添加了隐式优先级系统.在在新的Java阵列上进行SIP :

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

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

认为如果替代方法具有相同的参数类型,则该参数类型在子类中定义 胜利.因此,我相信您可以按以下方式声明隐式:

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天全站免登陆