3

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?

Community
  • 1
  • 1
Siva Prasad
  • 53
  • 1
  • 1
  • 4
  • you might want to look through this [http://www.scala-lang.org/api/current/index.html#scala.Array](http://www.scala-lang.org/api/current/index.html#scala.Array) – benji Dec 10 '14 at 02:44
  • class TestUser { var username = "" var password= "" var List = ArrayBuffer.empty[String] var DBFile = "" } For the above class if i have to initialize an array of objects var Users = ArrayBuffer[TestUser] returns an error – Siva Prasad Dec 10 '14 at 02:47
  • not sure what you mean by this... – benji Dec 10 '14 at 02:49

4 Answers4

2

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

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
1

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

  • val Users = Array.fill[TestUser](2)(TestUser()) does not work . class TestUser { var username = "" var password= "" var List = ArrayBuffer.empty[String] var DBFile = "" } – Siva Prasad Dec 10 '14 at 02:58
  • That's because your TestUser should be declared as 'case class', or you should create an instance with 'new', like `val users = Array.fill[TestUser](2)(new TestUser())` – Michael Nedokushev Dec 10 '14 at 11:27
1
var dice:Array[Dice]=new Array[Dice](2)
dice(0)=new Dice()
dice(1)=new Dice()

Array Of Objects in Scala

0

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

Leyth G
  • 1,103
  • 2
  • 15
  • 38