Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between :: and ::: in Scala

Tags:

scala

val list1 = List(1,2) val list2 = List(3,4) 

then

list1::list2 returns:  List[Any] = List(List(1, 2), 3, 4)  list1:::list2 returns:  List[Int] = List(1, 2, 3, 4) 

I saw the book writes that when use :: it also results List[Int] = List(1, 2, 3, 4). My Scala version is 2.9.

like image 297
Hesey Avatar asked Jul 04 '11 00:07

Hesey


People also ask

What is the difference between equals () and ==? Scala?

== is a final method, and calls . equals , which is not final. This is radically different than Java, where == is an operator rather than a method and strictly compares reference equality for objects.

What does := mean in Scala?

= performs assignment. := is not defined in the standard library or the language specification. It's a name that is free for other libraries or your code to use, if you wish.

How do you find the difference between two lists in Scala?

In Scala Stack class , the diff() method is used to find the difference between the two stacks. It deletes elements that are present in one stack from the other one. Return Type: It returns a new stack which consists of elements after the difference between the two stacks.

Does Scala use ==?

Methods: While == is an operator in several languages, Scala reserved The == equality for the natural equality of every type. it's a method in Scala, defined as final in Any. value equality will be tested by this.


2 Answers

:: prepends a single item whereas ::: prepends a complete list. So, if you put a List in front of :: it is taken as one item, which results in a nested structure.

like image 69
Debilski Avatar answered Sep 19 '22 14:09

Debilski


In general:

  • :: - 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

For example:

1 :: List(2, 3)             will return     List(1, 2, 3) List(1, 2) ::: List(3, 4)   will return     List(1, 2, 3, 4) 

In your specific question, using :: will result in list in a list (nested list) so I believe you prefer to use :::.

Reference: class List int the official site

like image 30
RafaelJan Avatar answered Sep 17 '22 14:09

RafaelJan