Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Nil while creating List in scala? [duplicate]

Tags:

list

scala

I have one basic question on List

I am getting the below error when I tried to create a List with cons operator

scala> val someList = 1::2
<console>:10: error: value :: is not a member of Int
   val someList = 1::2
                   ^

But if you look at below, as soon as I add Nil at end it works..

    scala> val someList = 1::2::Nil
    someList: List[Int] = List(1, 2)

I would like to know why is it Nil is needed atleast once at the end when we create a list

Is Nil a dataType? or empty element?

like image 293
Surender Raja Avatar asked Jun 10 '16 06:06

Surender Raja


1 Answers

Exactly because of this reason.

value :: is not a member of Int

In Scala, the operators are actually functions on objects. In this case, :: is a function on Nil object, which is actually an Empty list object.

scala> Nil
res0: scala.collection.immutable.Nil.type = List()

When you do 1::2, Scala looks for the function named :: on 2 and it doesn't find that. That is why it fails with that error.


Note: In Scala, if the last character of the operator is not colon, then the operator is invoked on the first operand. For example, 1 + 2 is basically 1.+(2). But, if the last character is colon, the the operator is invoked on the right hand side operand. So in this case, 1 :: Nil is actually Nil.::(1). Since, the :: returns another list object, you can chain it, like this 1 :: 2 :: Nil is actually, Nil.::(2).::(1).

like image 68
thefourtheye Avatar answered Oct 18 '22 10:10

thefourtheye