Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - How does method :: works in List?

Tags:

scala

I notice that List class define the method ::, which adds an element at the beginning 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 at How does scala compiler recognize such conversion? Because as far as I am concerned,

1 :: List(2,3)

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

Do I miss something about operator definition of scala?

like image 368
Eric Zheng Avatar asked Feb 14 '15 12:02

Eric Zheng


People also ask

How do you check if a value is in a list Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element. Otherwise, it returns false .

What are the different types of methods to create list in Scala?

Scala List Methods. head: This method returns the first element of the scala list. tail: This method returns all the elements except the first. isEmpty: This method checks if the list is empty in which case it returns True else False.

Which method returns a list consisting of all elements except the first in Scala?

tail: This method returns a list consisting of all elements except the first.

How do I append to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.


1 Answers

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

a foo_: b

is the same as

b.foo_:(a)

This rule exists specifically for the case of methods like this, which are commonly (in other languages such as Haskell and ML) operators like : or ::.

like image 168
Jörg W Mittag Avatar answered Sep 19 '22 18:09

Jörg W Mittag