Scala-为什么::不更改列表? [英] Scala - why does :: not change a List?

查看:99
本文介绍了Scala-为什么::不更改列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚编写了一些有趣的代码,但我有一个疑问,为什么它不起作用?

I have just written this code for some fun and I have a question why it isn't working out?

  val list = List[Int]()

  while (list.length < 20) {  
    Random.nextInt(100) :: list
  }

  println(list)
}

似乎没有任何内容写入列表,但是为什么会这样呢?我必须使其可变吗?为什么::运算符在这里不能正常工作?

Seems like nothing is written to the list, but why is that so? Do I have to make it mutable? And why is here the :: operator not working properly?

推荐答案

因为x :: xs返回一个新列表,其中第一个元素是x,后跟xs.

Because x :: xs returns a new list, where the first element is x, followed by xs.

因此,要使您的代码起作用,请将列表设为var,然后在循环内重新分配它:

So, to make your code work, make list a var and re-assign it inside the loop:

var list = List[Int]()

while(list.length < 20)
  list = Random.nextInt(100) :: list

但是,在Scala中这样做的惯用方式是根本不使用突变(尽管有时局部可变状态是可以的).通常,"While"循环可以用递归函数代替:

However, the idiomatic way of doing this in Scala is to not use mutations at all (local mutable state is fine sometimes though). "While" loops can usually be replaced with a recursive function:

def go(xs: List[Int]) =
  if (xs.length >= 20) xs
  else go(Random.nextInt(100) :: xs)

go(List())

也可以使用

This particular scenario can also be solved using List.fill instead

val list = List.fill(20)(Random.nextInt(100))

这篇关于Scala-为什么::不更改列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆