Is there a way to control which implicit conversion will be the default used?

前端 未结 1 1909
囚心锁ツ
囚心锁ツ 2020-11-29 07:40

Suppose I have this:

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


        
相关标签:
1条回答
  • 2020-11-29 08:03

    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
    }
    
    0 讨论(0)
提交回复
热议问题