Implicit scope

Now, let's move on to an example for the implicit scope, which has lower precedence than the lexical scope. The implicit scope usually includes (if applicable) the companion object of the type, the implicit scope of an argument's type, the implicit scope of type argument(s), and for nested types, outer objects.

The following example demonstrates the first three cases in action:

import scala.language.implicitConversions

trait ParentA { def name: String }
trait ParentB
class ChildA(val name: String) extends ParentA with ParentB

object ParentB {
implicit def a2Char(a: ParentA): Char = a.name.head

}
object ParentA {
implicit def a2Int(a: ParentA): Int = a.hashCode()
implicit val ordering = new Ordering[ChildA] {
override def compare(a: ChildA, b: ChildA): Int =
implicitly[Ordering[String]].compare(a.name, b.name)
}
}
object ChildA {
implicit def a2String(a: ParentA): String = a.name
}

trait Test {
def test(a: ChildA) = {
val _: Int = a // companion object of ParentA
val _: String = a // companion object of ChildA
val _: Char = a // companion object of ParentB
}
def constructor[T: Ordering](in: T*): List[T] = in.toList.sorted // companion object of type constructor
constructor(new ChildA("A"), new ChildA("B")).sorted // companion object of type parameters
}

Here, we spread a few implicit conversions in a class hierarchy to show how the lookup goes over companion objects of the argument and its supertypes, including supertraits. The last two lines demonstrate how the implicit scope includes type parameters of both the constructor and parameter type of the sorted method.

Unlike the first example, all implicits we defined in this one are unambiguous. If they aren't, the compiler would apply the static resolution rules to try to figure out the most specific implicit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.223