Is there a way that I can require objects being passed in to a function implement a core set of methods?
For example, I would like to be able to write a sum method to sum over any iterable of objects that implement the '+' operator.
My initial implementation is as follows
trait addable[T <: addable[T]]{
def +(other: T): T
}
def sum[T <: addable[T]](items: Iterable[T]) =
if(items.isEmpty) throw new Exception("Can't sum nothing")
else items.tail.foldRight(items.head)(_+_)
//Starst with the first element and adds all other elements to it
Now this method works, but it's clunky. If I want to have something be summable, I have to explicitly implement addable[T] in every class that I want to sum, not to mention define a bunch of explicit conversions for numeric types and strings.
Is there a way to implement it so that it looks something like this?
def sum[T fulfills addable[T]](items: Iterable[T]) =
if(items.isEmpty) throw new Exception("Can't sum nothing")
else items.tail.foldRight(items.head)(_+_)
Alternately, is there some design patter that removes the need for this (what I'm doing right now effectively seems to be little more than the adapter pattern)?