简体   繁体   English

{val x = a;是什么? b.:::(x)}在Scala中表示什么?

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

I am new to Scala and studying a book about it ( Programming in Scala ). 我是Scala的新手,正在学习一本有关它的书(《 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 但是实际上对于单参数方法,如果它不是模棱两可的话,scala允许跳过括号和点,这就是应该使用这种方法看起来不难看的方式

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 . 因此,键入x ::: b就像完成这种事情(x):::.b You obviously can't type it like this in scala, won't compile, but this is what happens. 您显然不能在scala中键入这样的内容,也不会进行编译,但这就是发生的情况。 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. 由于这个x在运算符的左侧,并且其元素将在此调用结果列表的左侧(开始)。

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? 哦,好了,现在我发现可能为您提供了更多说明,并且还发布了与您发布的代码相同的代码,以回答以下问题: Scala中的右关联方法有什么用?

Assuming a and b are lists: It assigns a to x , then returns the list b prepended with the list x . 假设a和b是列表:它将a分配给x ,然后返回以列表x开头的列表b

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) . 例如,如果val a = List(1,2,3)val b = List(4,5,6)则返回List(1,2,3,4,5,6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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