Scala - How does the :: method work in a List?

I notice that the List class defines a :: method that adds an item to the top of the list

 def ::(x: A): List[A] 

Example:

 1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3) 

However, I am confused by how the scala compiler recognizes such a conversion? Because as far as I know

 1 :: List(2,3) 

should raise error: :: is not a member of Int

Am I missing something about scala statement definition?

+6
source share
1 answer

Methods whose names end with : are right-associative when called using the infix operator notation. I.e.

 a foo_: b 

coincides with

 b.foo_:(a) 

This rule exists specifically for methods that are usually (in other languages ​​such as Haskell and ML), such as : or :: .

+14
source

Source: https://habr.com/ru/post/982486/


All Articles