Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I resize an array in Scala

I am trying to create a DB management tool in Scala, and I want to be able to draw from this database into Arrays, whose size can shift based on the data being passed to them. I know how to do this in C, PHP, VB, etc. but can't seem to figure out the syntax for Scala.

I'm sure this should be a simple problem, so any help would be appreciated

like image 852
Museless Avatar asked May 11 '26 16:05

Museless


2 Answers

Collections by default in Scala tend to be immutable. Operations will create new immutable collections from existing collections (by adding/removing elements etc.). The benefit of this is that collections don't change under iteration and writing multi-threaded applications tends to be easier (lots of caveats/assumptions with how you write standard Java apply here!).

Having said all that, if you need a mutable array, have you looked at an ArrayBuffer (a mutable collection with an underlying array implementation) ?

e.g.

val a = new scala.collection.mutable.ArrayBuffer[String]()
a += "A"
a += "B"
a(1)   // gives you 'B'
like image 148
Brian Agnew Avatar answered May 13 '26 08:05

Brian Agnew


You could use System.copy for this task, if you really want to use an array, or you could directly use a container that will resize itself automatically, such as ListBuffer or ArrayList.

like image 27
Geo Avatar answered May 13 '26 09:05

Geo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!