View bounds

The view bound is a syntactic sugar for the implicit parameter, which represents conversion between two types. It allows you to write a method signature with such implicit arguments in a slightly shorter form. We can see the difference between these two approaches by developing a method that will compare two unrelated types if there is a conversion to the third specific type for both of them:

case class CanEqual(hash: Int)

def equal[CA, CB](a: CA, b: CB)(implicit ca: CA => CanEqual, cb: CB => CanEqual): Boolean = ca(a).hash == ca(a).hash

The version with view bounds (similar to the upper bound and lower bound, which we discussed in Chapter 2Understanding Types in Scala) has a shorter definition:

def equalsWithBounds[CA <% CanEqual, CB <% CanEqual](a: CA, b: CB): Boolean = {
val hashA = implicitly[CA => CanEqual].apply(a).hash
val hashB = implicitly[CB => CanEqual].apply(b).hash
hashA == hashB
}

The implicit method we are using here is a helper method, which is defined in Predef as the following:

@inline def implicitly[T](implicit e: T) = e

This allows us to summon an implicit value of type T. We're not providing this implicit value explicitly, and so we need to help the compiler figure out the sequence of calls by using the apply method on the summoned conversion.

If the implementation is more complex as compared to the original version, why would we want to use it? The answer is this—it becomes much better if the implicit parameters were just passed over to some internal function:

def equalsWithPassing[CA <% CanEqual, CB <% CanEqual](a: CA, b: CB): Boolean = equal(a, b)

Like we said previously, view bounds have been deprecated since Scala 2.11, so we won't go into further details. Instead, we'll give our attention to context bounds.

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

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