You can initialize an array using the Array keyword. To know more about creating a Scala array, read: Scala Arrays
There are multiple ways to create a string array in Scala.
Method 1:
If you know all elements of the array in advance, you can initialize the Scala array in the following manner.
val arr_name = Array(element1, element2, ...)
Program:
object myObject
{
def main(args:Array[String])
{
val colors = Array("Red", "Blue", "Black", "Green")
println("This is an array of string :")
for(i <- 0 to colors.length-1){
println(colors(i))
}
}
}
Output
This is an array of string :
Red
Blue
Black
Green
Method 2:
If you don't know the elements of the string in advance but know the number of elements present in the array, then we will create an empty array of definite size first then feed elements to it.
val arr_name = new Array[String](number_of_elements)
Program:
object myObject
{
def main(args:Array[String])
{
val colors = new Array[String](3)
colors(0) = "Red"
colors(1) = "Blue"
colors(2) = "Black"
println("This is an array of string :")
for(i <- 0 to colors.length-1){
println("colors("+i+") : "+colors(i))
}
}
}
Output
This is an array of string :
colors(0) : Red
colors(1) : Blue
colors(2) : Black
Creating Mutable Strings Array in Scala
You can create a string array even when you do not know the size and element of the array. For this, we will create a mutable string. This mutable string is created using
ArrayBuffer class whereas others were created using Array class.
To create a mutable string we need to import mutable.ArrayBuffer in your program using,
Creating a string array in Scala
You can initialize an array using the Array keyword. To know more about creating a Scala array, read: Scala Arrays
There are multiple ways to create a string array in Scala.
Method 1:
If you know all elements of the array in advance, you can initialize the Scala array in the following manner.
Program:
Output
Method 2:
If you don't know the elements of the string in advance but know the number of elements present in the array, then we will create an empty array of definite size first then feed elements to it.
Program:
Output
Creating Mutable Strings Array in Scala
You can create a string array even when you do not know the size and element of the array. For this, we will create a mutable string. This mutable string is created using
ArrayBuffer class whereas others were created using Array class.
To create a mutable string we need to import mutable.ArrayBuffer in your program using,
Program:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer