Simple Scala string array examples

Scala array FAQ: How do I create a String array in Scala?

There are a few different ways to create String arrays in Scala. If you know all your array elements initially, you can create a Scala string array like this:

val fruits = Array("Apple", "Banana", "Orange")

If you don't know the strings that you want in your array initially, but know the size of your array, you can create it first, then populate it later, like this:

val fruits = new Array[String](3)

// somewhere later in the code ...

fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Orange"

Mutable Scala String arrays

Note that if you want to create a mutable Scala String array, you really want to use the Scala ArrayBuffer class instead of the Array class, like this:

import scala.collection.mutable.ArrayBuffer
var fruits = ArrayBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

See my Mutable Scala arrays (adding elements to arrays) tutorial for more information on using the Scala ArrayBuffer.

I can add more Scala String array syntax examples over time, but for now, those are the two most common approaches I know.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.