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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With