Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference and conversion between Seq[Int] and List[Int]

When I input Seq(1,2,3) in REPL, it returns me List(1,2,3)

scala> Seq(1,2,3)
res8: Seq[Int] = List(1, 2, 3)

Therefore, I thought the List(1,2,3) may be of type List[Int]. And I tried to specify the type for the variable who are assigned to Seq(1,2,3), but unexpectedly, the REPL complains like this:

scala> val a:List[Int]=Seq(1,2,3)
<console>:20: error: type mismatch;
 found   : Seq[Int]
 required: List[Int]
       val a:List[Int]=Seq(1,2,3)

Does anyone have ideas about what Seq[Int] = List(1, 2, 3) mean? Shouldn't it mean Seq(1,2,3) returns a list? What is the difference between Seq[Int] and List[Int]? And how to convert between Seq and List?

like image 736
Hanfei Sun Avatar asked Dec 15 '14 07:12

Hanfei Sun


People also ask

What is the difference between SEQ and list?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.

What is difference between list and sequence in Scala?

Sequence in Scala is a collection that stores elements in a fixed order. It is an indexed collection with 0 index. List is Scala is a collection that stores elements in the form of a linked list. Both are collections that can store data but the sequence has some additional features over the list.

What does seq mean in Scala?

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

What does ::: mean in Scala?

:: - adds an element at the beginning of a list and returns a list with the added element. ::: - concatenates two lists and returns the concatenated list.


1 Answers

Seq is a base trait (interface) for sequences and List is a concrete implementation of that interface.

Every instance of List is already a Seq so there's no need to convert anything. You can use toSeq method, but I don't see any reason to do so. To convert Seq to a List use toList method.

like image 181
Rado Buransky Avatar answered Sep 20 '22 01:09

Rado Buransky