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?

3
  • you might want to look through this http://www.scala-lang.org/api/current/index.html#scala.Array Commented Dec 10, 2014 at 2: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 Commented Dec 10, 2014 at 2:47
  • not sure what you mean by this... Commented Dec 10, 2014 at 2:49

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

val Users = Array.fill[TestUser](2)(TestUser()) does not work . class TestUser { var username = "" var password= "" var List = ArrayBuffer.empty[String] var DBFile = "" }
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())
1
var dice:Array[Dice]=new Array[Dice](2)
dice(0)=new Dice()
dice(1)=new Dice()

Array Of Objects in Scala

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.