3

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

amol
  • 66
  • 4

1 Answers1

4

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.

drexin
  • 23,521
  • 4
  • 61
  • 79