简体   繁体   中英

What does { val x = a; b.:::(x) } mean in Scala?

I am new to Scala and studying a book about it ( Programming in Scala ). I am really lost, what is the author trying to explain with the code below. Can anyone explain it in more detail ?

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

::: is a method that prepends list given as argument to the list it is called on

you could look at this as

val a = List(1, 2)
val b = List(3, 4)
val x = a

b.prependList(x)

but actually for single argument methods if it's not ambiguous scala allows to skip parenthesis and the dot and this is how this method is supposed to be used to not look ugly

x ::: b

it will just join these two lists, but there is some trick here

if method name ends with : it will be bound the other way

so typing x ::: b works as if this type of thing was done (x):::.b . You obviously can't type it like this in scala, won't compile, but this is what happens. Thanks to this x is on the left side of the operator and it's elements will be on the left side (beginning) of the list that is result of this call.

Oh well, now I found maybe some more explanation for you and also the very same piece of code you posted, in answer to this question: What good are right-associative methods in Scala?

Assuming a and b are lists: It assigns a to x , then returns the list b prepended with the list x .

For example, if val a = List(1,2,3) and val b = List(4,5,6) then it returns List(1,2,3,4,5,6) .

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