9

I am new to scala..I came across a concept where it says like below:

{ val x = a; b.:::(x) } 

In this block a is still evaluated before b, and then the result of this evaluation is passed as an operand to b’s ::: method

What is the meaning of above statement..
I tried like below:

var a =10
var b =20
What should be the result i should expect.
Can somebody please give me an example...

Thanks in advance....

1 Answer 1

9

The ::: operator is defined on List trait and concatenates two lists. Using it on Int like in your example (var a=10) shouldn't work (unless you define such operator yourself).

Here is how it works on lists:

val a = List(1, 2); val b = List(3, 4); val c1 = a ::: b // List(1, 2, 3, 4) val c2 = a.:::(b) // List(3, 4, 1, 2) 

Calling ::: with the infix syntax (c1) and method call syntax (c2) differ in the order in which lists are concatenated (see Jörg's comment).

The statement "a is still evaluated before b" means that a is evaluated before passing it as an argument to the method call. Unless the method uses call by name, its arguments are evaluated before the call just like in Java.

This could give you some hint how to search for meaning of Scala operators and keywords.

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

5 Comments

Thanks @Mifeet..Just had one question...Does it only support List and trait...Nice explanation....
I'm not sure I understand your answer, but AFAIK ::: is available only on objects inheriting from List. For other collections you can use ++.
"Calling ::: as with the infix syntax (c1) and method call syntax (c2) are equivalent." – No, they are not. Methods whose names end with : are right-associative when called with infix syntax, i.e. a ::: b is equivalent to b.:::(a), not a.:::(b) and evaluates to List(3, 4, 1, 2), not List(1, 2, 3, 4).
This answer is just wrong; the code clearly does not produce the outputs shown. As Jörg points out, c1 and c2 are not equivalent or even "almost equivalent", they are literally opposites.
Thank you for pointing that out, seems that I forgot to update the answer properly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.