Chapter 4

  1. Describe a case where an implicit parameter is also an implicit conversion.

This is the case if an implicit parameter is a function: def func[A, T](a: A)(implicit adapter: A => T): T  = adapter(a).

  1. Replace the following definition that uses view bounds with one using context bounds: def compare[T <% Comparable[T]](x: T, y: T) = x < y.
type ComparableContext[T] = T => Comparable[T]
def compare[T : ComparableContext](x: T, y: T) = x < y
  1. Why are type classes sometimes said to separate behavior and data?

Because type class instances define logic to work and the data comes from the values the type class is applied to.

It is easy to change the example of possible conflicts in lexical scope so that one of the implicits wins over others and all others can be uncommented without having conflicts anymore. Make this change. For example, it can be done by changing one of the definitions of vals to the definition of an object:

package object resolution {
// change // implicit val a: TS = new TS("val in package object") // (1)
// to //
implicit object TSO extends TS("object in package object") // (1)
}

Then, the TSO will be more specific than the rest of the values because of static resolution rules and will be selected by the compiler for the application.

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

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