bzak
bzak

Reputation: 495

Scala Why does the List class define a toList Method?

The scala docs define the following method in class List:

def toList: List[A]

As far as I can tell this method just returns a copy of our initial list. toList method

What is the use case of this method?

Upvotes: 2

Views: 2912

Answers (2)

Dima
Dima

Reputation: 40500

Consider something like this:

def bar(strings: List[String]) = strings.foreach(println)
def foo(ints: Seq[Int]) = bar(int.map(_.toString).toList)

foo(List(1,2,3))
foo(1 to 3)
foo(Stream.from(1).take(3))

etc.

foo accepts a Seq of ints, converts them to strings, and calls bar, that wants a List.

You can send any kind of Seq to foo, and it uses .toList to convert it to a List before invoking bar, because that's the only type it will accept. Now, if the argument to foo happens to already be List (like in the first example above), it will end up calling List.toList, which is just a nicer, more elegant alternative to making a special case in the code to check the concrete type of the argument.

Upvotes: 6

Tzach Zohar
Tzach Zohar

Reputation: 37832

List extends the GenTraversableOnce trait, which is a common trait for many other traversable collections.

GenTraversableOnce declares a toList method so that all subclasses can be converted into a List. This method must be implemented by List (and indeed - trivially by returning this).

Upvotes: 5

Related Questions