Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This answer describes another approach that results in more-readable, self-documenting client code.</p> <p><strong>Motivation</strong></p> <p>The <a href="https://stackoverflow.com/questions/4373070/how-do-i-get-an-instance-of-the-type-class-associated-with-a-context-bound/4373153#4373153"><code>context</code> method that I described previously</a> is a very general solution that works with any type class, without any additional effort. However, it may be undesirable for two reasons:</p> <ul> <li><p>The <code>context</code> method cannot be used when the type parameter has multiple context bounds, since the compiler has no way to determine which context bound is intended.</p></li> <li><p>The reference to the generic <code>context</code> method harms readability of the client code.</p></li> </ul> <p><strong>Type-class-specific methods</strong></p> <p>Using a method that is tied to the desired type class makes client code much more readable. This is the approach used in the standard library for the Manifest type class:</p> <pre><code>// definition in Predef def manifest[T](implicit m: Manifest[T]) = m // example usage def getErasure[T: Manifest](x: T) = manifest[T].erasure </code></pre> <p><strong>Generalizing this approach</strong></p> <p>The main drawback of using type-class-specific methods is that an additional method must be defined for every type class. We can ease this process with the following definitions:</p> <pre><code>class Implicitly[TC[_]] { def apply[T]()(implicit e: TC[T]) = e } object Implicitly { def apply[TC[_]] = new Implicitly[TC] } </code></pre> <p>Then a new type-class-specific implicitly-style method can be defined, for any type class:</p> <pre><code>def numeric = Implicitly[Numeric] // or val numeric = Implicitly[Numeric] </code></pre> <p>Finally, client code can use the Implicitly as follows:</p> <pre><code>def add[T: Numeric](x: T, y: T) = numeric[T].plus(x, y) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload