'Simple Scala string array examples'에 해당되는 글 1건

  1. 2014.03.28 Simple Scala string array examples
00.scala2014. 3. 28. 13:20
반응형

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

Posted by 1010