Siva Prasad
Siva Prasad

Reputation: 53

Create an array of objects in scala

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

Bubble[] bubble = new Bubble[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

Can anyone please help me out?

Upvotes: 3

Views: 16962

Answers (4)

Leyth G
Leyth G

Reputation: 1143

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

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

Upvotes: 0

Bibil Mathew Chacko
Bibil Mathew Chacko

Reputation: 11

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

Array Of Objects in Scala

Upvotes: 1

Jordan Parmer
Jordan Parmer

Reputation: 37174

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.

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

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

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

Upvotes: 2

Michael Nedokushev
Michael Nedokushev

Reputation: 50

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().

Upvotes: 1

Related Questions