top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between :: and #:: in Scala? What is the difference between ::: and #::: in Scala?

+2 votes
301 views
What is the difference between :: and #:: in Scala? What is the difference between ::: and #::: in Scala?
posted Jun 28, 2016 by Shivam Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

In Scala Collection API,

:: and ::: are methods available in List class.

:: and #::: are methods available in Stream class

In List class, :: method is used to append an element to the beginning of the list.

scala> var list1 = List(1,2,3,4)
list1: List[Int] = List(1, 2, 3, 4)

scala> list1 = 0 :: list1
list1: List[Int] = List(0, 1, 2, 3, 4)
In List class, ::: method is used to concatenate the elements of a given list in front of this list.

scala> var list1 = List(3,4,5)
list1: List[Int] = List(3, 4, 5)

scala> val list2 = List(1,2) ::: list1
list2: List[Int] = List(1, 2, 0, 1, 2, 3, 4)

In Stream class, #:: method is used to append a given element at beginning of the stream. Only this newly added element is evaluated and followed by lazily evaluated stream elements.

scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> s1 = 0 #:: s1
s1: scala.collection.immutable.Stream[Int] = Stream(0, ?)
In Stream class, #::: method is used to concatenate a given stream at beginning of the stream. Only this newly added element is evaluated and followed by lazily evaluated stream elements.

scala> var s1 = Stream(1,2,3,4)
s1: scala.collection.immutable.Stream[Int] = Stream(1, ?)

scala> val s2 = Stream(-1,0) #::: s1
s2: scala.collection.immutable.Stream[Int] = Stream(-1, ?)

:: method works as a cons operator for List class and #:: method words as a cons operator for Stream class. Here ‘cons’ stands for construct.
::: method works as a concatenation operator for List class and #::: method words as a concatenation operator for Stream class.

answer Jul 18, 2016 by Karthick.c
...