Nil is the main building block for creating a List as a recursive data structure. The list is a useful data structure that provides O (1) time access to the head (first element).
List on it the minimal core built on 3 operations of head , tail and isEmpty . Nil is a single-class subclass of the List class, so it is a special instance of its type, representing an empty list . The cons :: operator is defined in List to build a list recursively by adding one element to the list.
See definition of List attribute and Nil object (very simplified)
trait List[A] { def head: A def tail: List[A] def isEmpty: Boolean } case object Nil extends List[Nothing] { def head = throw new NoSuchElementException("head of empty list") def tail = throw new UnsupportedOperationException("tail of empty list") def isEmpty = true }
Since any identifier / operator that ends with : is bound to the right, the :: operator is also bound to the right.
When you write 1::2::3 , scala tries to rewrite these calls as 3.::(2.::(1)) . those. 3 becomes the receiver of the first :: call, which does not exist on any arbitrary data type (Int in this case).
That's why you always build up on an empty list - Nil. Think of it as adding each item one by one to an empty Nil list.
Pranav shukla
source share