Arrays in Scala are mutable, fixed-size data structures that store elements of the same type. They provide efficient random access and are zero-indexed, making them suitable for various programming tasks.
There are multiple ways to create arrays in Scala:
val numbers = new Array[Int](5)
val names = new Array[String](3)
val fruits = Array("apple", "banana", "orange")
val scores = Array(85, 92, 78, 90)
Array elements can be accessed and modified using index notation:
val colors = Array("red", "green", "blue")
println(colors(1)) // Output: green
colors(2) = "yellow"
println(colors.mkString(", ")) // Output: red, green, yellow
val numbers = Array(1, 2, 3, 4, 5)
println(numbers.length) // Output: 5
numbers.foreach(println) // Prints each number on a new line
val doubled = numbers.map(_ * 2)
println(doubled.mkString(", ")) // Output: 2, 4, 6, 8, 10
val evenNumbers = numbers.filter(_ % 2 == 0)
println(evenNumbers.mkString(", ")) // Output: 2, 4
val sliced = numbers.slice(1, 4)
println(sliced.mkString(", ")) // Output: 2, 3, 4
Scala supports multi-dimensional arrays, which are essentially arrays of arrays:
val matrix = Array(
Array(1, 2, 3),
Array(4, 5, 6),
Array(7, 8, 9)
)
println(matrix(1)(2)) // Output: 6
While arrays are mutable and fixed-size, Scala Lists are immutable and have a more functional approach. Choose arrays when you need efficient random access and mutability, and lists when you prefer immutability and functional operations.
Arrays are fundamental data structures in Scala, offering a balance between performance and functionality. Understanding their properties and operations is crucial for effective Scala programming.