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....

Mifeet
  • 12,949
  • 5
  • 60
  • 108
Amaresh
  • 3,231
  • 7
  • 37
  • 60

1 Answers1

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.

Community
  • 1
  • 1
Mifeet
  • 12,949
  • 5
  • 60
  • 108
  • Thanks @Mifeet..Just had one question...Does it only support List and trait...Nice explanation.... – Amaresh Aug 27 '15 at 12:12
  • I'm not sure I understand your answer, but AFAIK `:::` is available only on objects inheriting from `List`. For other collections you can use [++](http://stackoverflow.com/a/6560117/2032064). – Mifeet Aug 27 '15 at 12:24
  • 6
    "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)`. – Jörg W Mittag Aug 27 '15 at 16:50
  • 1
    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. – dhg Mar 01 '16 at 02:20
  • Thank you for pointing that out, seems that I forgot to update the answer properly. – Mifeet Mar 01 '16 at 09:26