在 Scala 中创建对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27392505/
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 06:46:33  来源:igfitidea点击:

Create an array of objects in scala

scala

提问by Siva Prasad

I have been trying to figure out on how to create an Array of Objects like we have the below in Java.

我一直在试图弄清楚如何创建一个对象数组,就像我们在 Java 中拥有的一样。

Bubble[] bubble = new Bubble[2];

泡泡[] 泡泡 = 新泡泡[2];

I have defined a class as below:

我定义了一个类如下:

class  TestUser {
    var username = ""
    var password= ""
    var List = ArrayBuffer.empty[String]
    var DBFile = ""
 }

I have to create an array of objects of the above class.

我必须创建上述类的对象数组。

Like in Java --> How to initialize an array of objects in Java

就像在 Java 中一样 -->如何在 Java 中初始化对象数组

Can anyone please help me out?

任何人都可以帮我吗?

采纳答案by Michael Nedokushev

Hmmm, are you serious? Okay...

嗯,你是认真的吗?好的...

val bubble = Array.fill[Bubble](2)(Bubble())

The first argument defines a size, and the second just initializes array with values of Bubble().

第一个参数定义了一个大小,第二个参数只是用 Bubble() 的值初始化数组。

回答by Jordan Parmer

I think you should step back and research collections in Scala. In Scala, it is not conventional to use an Array type but to instead use the extremely powerful collections library.

我认为你应该退后一步研究 Scala 中的集合。在 Scala 中,使用 Array 类型并不是传统的做法,而是使用极其强大的集合库。

Be wary of trying to "do Java in Scala".

小心尝试“在 Scala 中执行 Java”。

Take a look at Lists, Sequences, etc. and become familiar with immutable patterns to handle collections.

看看列表、序列等,熟悉处理集合的不可变模式。

https://twitter.github.io/scala_school/collections.html

https://twitter.github.io/scala_school/collections.html

回答by Bibil Mathew Chacko

var dice:Array[Dice]=new Array[Dice](2)
dice(0)=new Dice()
dice(1)=new Dice()

Array Of Objects in Scala

Scala 中的对象数组

回答by Leyth G

I would recommend reading this to gain proper understanding of mutable and immutable collections in Scala.

我建议阅读本文以正确理解 Scala 中的可变和不可变集合。

http://docs.scala-lang.org/overviews/collections/overview.html

http://docs.scala-lang.org/overviews/collections/overview.html