简体   繁体   中英

What is the difference between ::: and :::.() in scala

In the scala list class it is shown that:

List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4) . Shouldn't:

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

( method ::: prefixes the list)

I think that what you are doing with List(1,2).:::(List(3,4)) is changing the order of things.

Ending with : makes scala want to call the method on the object to the right. So

a :: b

is really

b.::(a)

When being explicit with the dots and parentheses, you change the order.

Not sure if this example makes it clearer:

scala> class X() {
     def `a:`(s: String): Unit = {
     println(s)
  }}

scala> var x = new X()
scala> x.`a:`("X")
X
scala> x `a:` "X"
<console>:10: error: value a: is not a member of java.lang.String
          x `a:` "X"
            ^

You see that scala wants to call the a: method on the string object on the right.

From the docs :

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

[use case] Adds the elements of a given list in front of this list.

Example:

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

In Scala, operators that end in : are right associative and the invoking object appears on the right side of the operator. Because it is right associative, the prefix method will be called on the object "to the right", which is List(3, 4) .

Then it will do what its name says, it will prefix List(3, 4) with List(1, 2) , and that's why you get List(1, 2, 3 ,4) . Not the most intuitive thing in the world but it's like this:

a ::: b
// ending in :, so flip the argument order, call the method on b.
b .:: a // :: = prefix b with a
result = a(concatenated) with b

Now let's look at the right hand side:

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

The . dot is performing an inversion of the ::: prefixed invocation, so it will simply invert the two List objects before performing the ::: prefix operation.

List(3, 4).:::(List(1,2)) = List(1, 2) ::: List(3, 4) // exactly as the above.
// and now you it's the same story.

The . dot is a simply way to invert associative operators. a ::: b is the same as b .::: a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM