Reputation: 11
Sorry if this has been covered already. The following simple example of dynamic typing and type bounds does not work with a list of strings but works perfectly well with a (scala) class containing a defined length() function. Is this expected behavior or a bug? If it is expected behavior, is there a way to define the type bound such that it would work for a List of String objects as well as a list of arbitrary scala objects with a length(0 function?
def sumlen[T <: {def length : Int}](l : List[T]) : Int = {
def sl(l : List[T], acc : Int) : Int = l match {
case Nil => acc
case h::t => sl(t, h.length + acc)
}
sl(l, 0)
}
val l1 = List("This", "is", "a", "test")
sumlen(l1)
Upvotes: 1
Views: 160
Reputation: 6114
This works:
def sumlen[T <: {def length() : Int}](l : List[T]) : Int = {
// ^^
And yes, it is a feature, not a bug.
Upvotes: 2