Reputation: 66
What is the difference between following two declarations of sum functions?
def sum[A](xs:List[A]) = .....
def sum[A <: List[A]](xs:A) = ....
EDIT: To elaborate more....
Lets say I want to write a method head on List.
I can write head as follow:
def head[A](xs:List[A]) = xs(0)
or else we can write
def head[A <: List[A]] (xs:A) = xs(0)
Which one to prefer and when?
Note: one difference I figured out that implicit conversions are not applied for second one
Upvotes: 3
Views: 792
Reputation: 24413
The first one takes a List[A]
as parameter, the second one some A
that is a subtype of List[A]
. Consider the following example:
scala> trait Foo[A <: Foo[A]]
defined trait Foo
scala> class Bar extends Foo[Bar]
defined class Bar
The recursive type parameter on Foo
can be useful, when you want to define a method in the trait that takes or returns the type of the subclass:
trait Foo[A <: Foo[A]] {
def f: A
}
class Bar extends Foo[Bar] {
def f: Bar = new Bar
}
class Baz extends Foo[Baz] {
def f: Baz = new Baz
}
I don't know how your specific example should work, because I don't know how you would sum on that type.
Upvotes: 4