Given the following code:
abstract class Field {
type T
val data: List[T]
def sum: T = data(0) + data(1)
}
I get an error on the last line – def sum: T = data(0) + data(1):
types2.scala:6: error: type mismatch;
found : Field.this.T
required: String
def sum: T = data(0) + data(1)
^
That is, it expects data(1) to be a String.
I dont understand why… (scala 2.8.1)
Your explanation will be much appreciated!
Since
Tdoes not support an addition operation, compiler assumes+to be a string concatenation operation. The following line I tried out at REPL indicates so:What you can do is require that
Thave aSemigroupalgebra defined. (A type is a semigroup if it supports an associative append operation.)I replaced abstract type by a type parameter simply because I do not know how to put a context bound on an abstract type. I also changed type of data from
List[A]toIndexedSeq[A]because as the name indicates indexed sequences are more suitable for indexed access than lists (which is what you do in yoursummethod). And finally,|+|is the semigroup append operation. For numeric types it will perform addition. For sequences, concatenation etc.