public
Last active

implicit resolution examples

  • Download Gist
ImplicitResolution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
object ImplicitResolution {
object CompanionObject {
implicit def convert(co: CompanionObject) = "o: co/p: co"
implicit def convert(co: CompanionObject2) = "o: co/p: co2"
implicit def convert(from:String) = new CompanionObject
}
class CompanionObject
 
object CompanionObject2 {
implicit def convert(s: CompanionObject) = "o: co2/p: co"
implicit def convert(s: CompanionObject2) = "o: co2/p: co2"
implicit def convert(sl: List[String]) = sl.size
}
class CompanionObject2
 
def main(args: Array[String]) {
//conversion from companion object is picked by default
println(new CompanionObject: String)
println(new CompanionObject2: String)
println("targetTypeCompanionObjectsAreAlsoSearched":CompanionObject)
//import overrides conversion from companion object via import
import CompanionObject2._
println(new CompanionObject: String)
println(new CompanionObject2: String)
//not possible, would lead to ambiguous conversions
//import CompanionObject._
 
// picks conversion declared later in class
println(new CompanionObject: Int)
 
val list = List("a", "b")
//picks conversion from CompanionObject2 because the conversion is imported
println(list: Int)
 
// not possible, would shadow conversion of CompanionObject and then become a forward reference
//implicit def convert(ol: Traversable[Any]) = ol.size + 1
 
// does not shadow existing conversions, thus not causing a forward ref error
implicit def convertRenamed(ol: Traversable[Any]) = ol.size + 1
//still uses the implicit from CompanionObject2 because the method signature is more specific
println(list: Int)
// inner block allows to override outer implicits without creating ambiguity-problems
val u = {
implicit def convert(ol: List[String]) = ol.size + 2
println(list: Int) //now uses new conversion
//implicit def convert2(ol: List[String]) = ol.size + 3 // no name shadowing, but ambiguity again, won't compile
}
u
}
 
//implicit conversions must be defined before they are used or have an explicit result type
implicit def convert(c: CompanionObject): Int = 99

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.