在 Scala 中附加到 Seq

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43992716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 09:14:50  来源:igfitidea点击:

Appending to Seq in Scala

scala

提问by ps0604

The following code is supposed to append to a Seq, but it prints an empty list, what's wrong here?

下面的代码应该附加到一个 Seq,但它打印了一个空列表,这里有什么问题?

object AppendToSeq extends App{

    val x = Seq[Int]()

    x :+ 1
    x :+ 2

    println(x)

}

回答by rogue-one

the value x created is an immutable Sequence and the method :+defined on the immutable sequence return a new Seq object.

创建的值 x 是一个不可变的序列,并且在不可变序列上:+定义的方法 返回一个新的 Seq 对象。

so your code should have x has a var (a mutable variable) and it should have its value re-assigned after each append (:+) operation as shown below.

所以你的代码应该有 x 有一个 var(一个可变变量),它应该在每次 append ( :+) 操作后重新分配它的值,如下所示。

scala> var x = Seq[Int]()
x: Seq[Int] = List()

scala> x = x :+ 1
x: Seq[Int] = List(1)

scala> x = x :+ 2
x: Seq[Int] = List(1, 2)

scala> x
res2: Seq[Int] = List(1, 2)

回答by jwvh

x :+ 1creates a new Seqby appending 1to the existing Seq, x, but the new Seqisn't saved anywhere, i.e. it isn't assigned to any variable, so it's just thrown away.

x :+ 1Seq通过附加1到现有的Seq,创建一个新的x,但新Seq的没有保存在任何地方,即它没有分配给任何变量,所以它只是被扔掉了。

If you want to modify an existing Seqyou can make the variable a varinstead of a val. Then when you create a new Seqyou can save it under the same name.

如果你想修改一个现有的,Seq你可以使变量 avar而不是 a val。然后当你创建一个新的时,Seq你可以用相同的名称保存它。

scala> var x = Seq[Int]()
x: Seq[Int] = List()

scala> x = x :+ 7
x: Seq[Int] = List(7)