Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using Scala 2.8, you could write:</p> <pre><code>case class Vector3[T: Numeric](val x: T, val y: T, val z: T) { override def toString = "(%s, %s, %s)" format (x, y, z) def add(that: Vector3[T]) = new Vector3( plus(x, that.x), plus(y, that.y), plus(z, that.z) ) private def plus(x: T, y: T) = implicitly[Numeric[T]] plus (x, y) } </code></pre> <p>Let me explain. First, <code>T: Numeric</code> is a context bound that implicitly provides a <code>Numeric[T]</code> instance to your class. </p> <p>The <code>Numeric[T]</code> trait provides operations on numeric types,</p> <pre><code>trait Numeric[T] extends Ordering[T] { def plus(x: T, y: T): T def minus(x: T, y: T): T def times(x: T, y: T): T def negate(x: T): T // other operations omitted } </code></pre> <p>The expression <code>implicitly[Numeric[T]]</code> retrieves this implicit context such that you can perform the operations such as <code>plus</code> on your concrete arguments x, y and z, as illustrated in the private method above.</p> <p>You can now construct and <code>add</code> different instantiations of <code>Vector3</code> such as with <code>Int</code>'s and <code>Double</code>'s:</p> <pre><code>scala&gt; Vector3(1,2,3) add Vector3(4,5,6) res1: Vector3[Int] = (5, 7, 9) scala&gt; Vector3(1.1, 2.2, 3.3) add Vector3(4.4, 5.5, 6.6) res2: Vector3[Double] = (5.5, 7.7, 9.899999999999999) </code></pre> <p>Side-note: It's possible to use implicit conversions to convert values to <code>Numeric[T].Ops</code> instances such that the following could be written instead:</p> <pre><code> def add(that: Vector3[T]) = new Vector3(x + that.x, y + that.y, z + that.z) </code></pre> <p>I've deliberately chosen not to use these implicit conversions since they (may) incur some performance penalty by creating temporary wrapper objects. Actual performance impact depends on the JVM (e.g., to which extent its supports escape analysis to avoid actual object allocation on heap). Using a context bound and <code>implicitly</code> avoids this potential overhead ... at the cost of some verbosity.</p>
    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. 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