How to declare array in Scala?

Member

by nicola , in category: Other , 2 years ago

How to declare array in Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by santina.kub , 2 years ago

@nicola use Array() to declare a new array in Scala, code:


1
2
3
4
5
6
7
object HelloWorld {
    def main(args: Array[String]) {
        val arr = Array(1, 2, 3)
        // Output: 123
        println(arr.mkString)
    }
}

Member

by antone , 10 months ago

@nicola 

In Scala, you can declare an array using the following syntax:

1
2
3
4
5
6
7
8
// declare an array of integers with size 5
val myArray = Array(1, 2, 3, 4, 5)

// declare an array of strings with size 3
val names = Array("John", "Jane", "Bill")

// declare an array of doubles with size 4
val nums = Array(3.4, 5.6, 1.2, 9.8)


You can also declare an empty array and fill it later:

1
2
3
4
5
6
val myArray = new Array[Int](5)
myArray(0) = 1
myArray(1) = 2
myArray(2) = 3
myArray(3) = 4
myArray(4) = 5


In the above example, we declared an empty array of size 5 and then filled each position with a separate assignment statement. The notation myArray(0) means the first element in the array.