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

1

20

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.

Johnsonjohnsonese answered 11/12, 2009 at 9:48 Comment(3)
Possible duplicate: #1339648Danu
I don't think it's a duplicate. The author of that question wanted to keep both implicits. I only want one.Johnsonjohnsonese
There's a very similar, if not identical, method to the above already available in RichString. If you want your method to be used, perhaps you can use the import a.b.{c => _} technique to hide c where c is the implicit method name.Bedew
N
34

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
}
Neapolitan answered 11/12, 2009 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.