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, ...

Get Learn Scala Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.