问题描述
假设我有这个:
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 subclasswins. Hence I believe that you could declare implicits as follows:
trait LowPriorityImplicits {
//lower priority conversions
}
object HighPriorityImplicits extends LowPriorityImplicits {
//higher-order ones here
}
这篇关于有没有一种方法可以控制默认使用哪种隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!