Scala Arrays
Scala Arrays
Section titled “Scala Arrays”An Array[T] in Scala is a mutable, fixed-size, indexed sequence of elements of type T. Arrays provide efficient random access to elements based on their index (starting from 0). They are directly mapped to Java arrays.
Note: While arrays are available and useful for performance-critical code or Java interop, idiomatic Scala often prefers immutable collections like Vector or List for general-purpose sequences, as they align better with functional programming principles.
Declaring and Creating Arrays:
Section titled “Declaring and Creating Arrays:”You can create arrays in several ways:
// 1. Using 'new' with size (elements initialized to default: 0, false, null)val numbers = new Array[Int](5) // Array of 5 integers, initialized to 0val flags = new Array[Boolean](3) // Array of 3 booleans, initialized to falseval strings = new Array[String](2) // Array of 2 Strings, initialized to null
// 2. Using the companion object's 'apply' factory method (preferred)val names = Array("Alice", "Bob", "Charlie") // Type inferred: Array[String]val primes = Array(2, 3, 5, 7) // Type inferred: Array[Int]val mixed = Array(1, "two", 3.0) // Type inferred: Array[Any]
// 3. Creating an empty arrayval emptyInts = Array.empty[Int]Accessing and Modifying Elements:
Section titled “Accessing and Modifying Elements:”Use parentheses () with the index to access or update elements. Remember that arrays are 0-indexed.
val fruits = Array("Apple", "Banana", "Orange")
// Access elementsval firstFruit = fruits(0) // "Apple"val secondFruit = fruits(1) // "Banana"
// Modify elements (Arrays are mutable)fruits(1) = "Mango"// Now fruits is Array("Apple", "Mango", "Orange")
@main def ArrayAccessDemo(): Unit = { println(s"First fruit: $firstFruit") println(s"Updated fruits: ${fruits.mkString(", ")}") // mkString is useful for display // Accessing out of bounds causes ArrayIndexOutOfBoundsException // println(fruits(3))}Processing Arrays:
Section titled “Processing Arrays:”You can iterate and process arrays using for comprehensions or standard collection methods.
val data = Array(1.5, 2.0, 3.5, 4.0)
// Iteration using for loopprintln("Processing with for loop:")var sum = 0.0for (x <- data) { println(s"Processing $x") sum += x}println(s"Sum: $sum")
// Iteration using indicesvar product = 1.0for (i <- 0 until data.length) { // Use 'until' for exclusive range product *= data(i)}println(s"Product: $product")
// Using collection methods (more functional style)val increasedData = data.map(x => x + 0.1)println(s"Increased data: ${increasedData.mkString(", ")}")
val largeValues = data.filter(x => x > 2.5)println(s"Large values: ${largeValues.mkString(", ")}")
data.foreach(x => println(s"Element: $x")) // Side-effecting iterationMulti-Dimensional Arrays:
Section titled “Multi-Dimensional Arrays:”Scala supports multi-dimensional arrays using Array.ofDim.
// Create a 2x3 matrix (2 rows, 3 columns) of integersval matrix = Array.ofDim[Int](2, 3)
// Initialize the matrixfor (row <- 0 until matrix.length) { for (col <- 0 until matrix(row).length) { matrix(row)(col) = row * 10 + col }}
// Print the matrix@main def MultiDimArrayDemo(): Unit = { println("Matrix:") for (row <- matrix) { // Iterate through rows (which are arrays) println(row.mkString("\t")) // Print each row } // Access specific element println(s"Element at (1, 2): ${matrix(1)(2)}") // Output: 12}Output:
Matrix:0 1 210 11 12Element at (1, 2): 12Common Array Operations:
Section titled “Common Array Operations:”Many useful methods are available directly or via the Array companion object.
| Method/Operation | Description |
|---|---|
length | Get the size of the array. |
apply(index) | Access element at index (used via myArray(index) syntax). |
update(index, value) | Modify element at index (used via myArray(index) = value syntax). |
map, filter, foreach | Standard functional collection methods. |
mkString(sep) | Convert array elements to a string with a separator. |
++ | Concatenate two arrays (returns a new array). |
head, tail, last, init | Access first/last elements or subsequences. |
slice(from, until) | Extract a subarray. |
sorted | Return a new sorted array (requires Ordering). |
sum, min, max, product | Aggregate methods for numeric arrays. |
Array.fill(n)(elem) | Create an array of size n filled with elem. |
Array.tabulate(n)(f) | Create an array of size n where element i is f(i). |
Array.range(start, end, step) | Create an array with elements in a range. |
Example: Concatenation and Range
Section titled “Example: Concatenation and Range”val arr1 = Array(1, 2)val arr2 = Array(3, 4)val combined = arr1 ++ arr2 // Array(1, 2, 3, 4)
val evens = Array.range(0, 10, 2) // Array(0, 2, 4, 6, 8)
@main def ArrayOpsDemo(): Unit = { println(s"Combined: ${combined.mkString(", ")}") println(s"Evens: ${evens.mkString(", ")}")}