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