Skip to content

Instantly share code, notes, and snippets.

@HamsterofDeath
Created January 20, 2012 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HamsterofDeath/1649497 to your computer and use it in GitHub Desktop.
Save HamsterofDeath/1649497 to your computer and use it in GitHub Desktop.
implicit resolution examples
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment