2

I am learning scala and I've noticed that the following line of code doesn't work

     val worldFreq = ("India", 1) :: ("US", 2) :: ("Berlin", 10)

Results in the error : error: value :: is not a member of (String, Int) val worldFreq = ("India", 1) :: ("US", 2) :: ("Berlin", 10)

However this line of code works perfectly

val worldFreq = ("India", 1) :: ("US", 2) :: ("Berlin", 10) :: Nil
worldFreq: List[(String, Int)] = List((India,1), (US,2), (Berlin,10))

Can someone help me understand the error message and the fact the it works with Nil.

Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106
  • ("India", 1) :: ("US", 2) :: ("Berlin", 10)::Nil do this it will work you are using :: operator on a tuple which is not the member of a tuple you can use it on List – Raman Mishra Aug 31 '18 at 10:37
  • Possible duplicate of [Scala's '::' operator, how does it work?](https://stackoverflow.com/questions/2827293/scalas-operator-how-does-it-work) – Raman Mishra Aug 31 '18 at 10:48

1 Answers1

3

It happens because :: is right-associative operator.

So, when you type (1, 2) :: Nil it transforms to Nil.::((1,2)). And obviously, there is no :: method on tuples, so you can't write (1, 2) :: (3, 4).

You can read more here: Scala's '::' operator, how does it work?

Yevhenii Popadiuk
  • 1,024
  • 7
  • 18