So I’m learning Scala at the moment, and I’m trying to create an abstract vector class with a vector-space of 3 (x,y,z coordinates). I’m trying to add two of these vectors together with the following code:
package math
class Vector3[T](ax:T,ay:T,az:T) {
def x = ax
def y = ay
def z = az
override def toString = "<"+x+", "+y+", "+z+">"
def add(that: Vector3[T]) = new Vector3(x+that.x, y+that.y, z+that.z)
}
The problem is I keep getting this error:
error: type mismatch;
found :
T
required: String
def
add(that: Vector3[T]) = new
Vector3(x+that.x, y+that.y,
z+that.z)
I’ve tried commenting out the “toString” method above, but that doesn’t seem to have any effect. Can anyone tell me what I’m doing wrong?
Using Scala 2.8, you could write:
Let me explain. First,
T: Numericis a context bound that implicitly provides aNumeric[T]instance to your class.The
Numeric[T]trait provides operations on numeric types,The expression
implicitly[Numeric[T]]retrieves this implicit context such that you can perform the operations such aspluson your concrete arguments x, y and z, as illustrated in the private method above.You can now construct and
adddifferent instantiations ofVector3such as withInt‘s andDouble‘s:Side-note: It’s possible to use implicit conversions to convert values to
Numeric[T].Opsinstances such that the following could be written instead: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
implicitlyavoids this potential overhead … at the cost of some verbosity.