Start Coding

Topics

Scala Arrays

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.

Creating Arrays

There are multiple ways to create arrays in Scala:

1. Using the Array constructor

val numbers = new Array[Int](5)
val names = new Array[String](3)

2. Using array literals

val fruits = Array("apple", "banana", "orange")
val scores = Array(85, 92, 78, 90)

Accessing and Modifying Array Elements

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

Common Array Operations

  • length: Get the number of elements in the array
  • foreach: Iterate over array elements
  • map: Transform array elements
  • filter: Select elements based on a condition
  • slice: Extract a portion of the array
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

Multi-dimensional Arrays

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

Array vs. List

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.

Best Practices

  • Use arrays when you need mutable, fixed-size collections with fast random access.
  • Consider using Scala Vectors for immutable, indexed sequences with good performance characteristics.
  • Leverage Scala Collection Operations for powerful data manipulation.
  • Be cautious with large arrays, as they can consume significant memory.

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.