0

I'm new to scala and just playing around with it in my free time and ran into this problem:

if I have this list:

 val list = List(1,2,3,4)

and then say:

 val newList = list :: 5

scala tells me

 error: value :: is not a member of Int

but if I say:

 val newList = list ::: List(5)

scala is completely alright with it. Why can I not append an element to a List, but I can append all elements of a List to the end of a List

1 Answer 1

7

You've got the syntax backwards:

5 :: list

This will prepend the element 5 to the front of list.

In Scala, operators that end with a colon (:) are right-associative. So 5 :: list calls the :: method on list and gives the argument 5.

The reason list ::: List(5) works is that it's actually prepending list to the front of List(5).

By the way, List also has the operators +: and :+ for prepend and append, respectively. (But keep in mind that prepending to a List is O(1) while appending is O(n).)

Sign up to request clarification or add additional context in comments.

1 Comment

ohhh alright so i was actually saying 5.::(list) ok. So that explains the error message then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.