array
Scala Arrays
- Overview: Arrays in Scala are a direct mapping to Java's arrays. They provide a sequence of elements that are indexed and have a fixed size. Scala arrays can store any type of elements, including AnyVal (value types) and AnyRef (reference types).
- Creating Arrays:
val nums = Array(1, 2, 3, 4) val names = Array("Alice", "Bob", "Charlie") - Accessing Elements: Arrays allow random access to their elements through an index.
val firstNum = nums(0) // Accessing the first element nums(2) = 10 // Updating the third element - Key Properties:
- Fixed size but mutable in terms of element values.
- Can be multidimensional.
Basic Operations
- Length of an Array: Use the
lengthproperty to get the size of an array.val size = nums.length - Iterating Over Arrays: You can use a
forloop or higher-order functions likeforeach.for (name <- names) println(name) names.foreach(println) - Modifying Elements: Elements can be updated by specifying their index.
nums(0) = 100 // Update the first element to 100
Common Methods
- Mapping and Filtering:
Arrays support functional programming methods such as
mapandfilter.val squaredNums = nums.map(x => x * x) val evenNums = nums.filter(_ % 2 == 0) - Sorting Arrays:
Use the
sortedmethod orsortWithfor custom sorting.val sortedNames = names.sorted val descendingNums = nums.sortWith(_ > _)
Multidimensional Arrays
- Creating and Using Multidimensional Arrays:
Scala supports arrays of arrays, allowing for multidimensional structures.
val matrix = Array.ofDim[Int](2, 2) // 2x2 matrix matrix(0)(0) = 1 matrix(0)(1) = 2 matrix(1)(0) = 3 matrix(1)(1) = 4
Converting Between Arrays and Other Collections
- To and From Collections:
Arrays can be converted to and from other Scala collections like List, Seq, etc.
val numList = nums.toList val numSeq = nums.toSeq val arrayFromList = numList.toArray
Best Practices
- When to Use Arrays:
- Choose arrays for performance-sensitive, low-level programming tasks.
- Ideal when working with a fixed-size collection of elements.
- Interoperability with Java:
- Arrays provide seamless interoperability with Java methods that require Java's native arrays.
- Immutability vs. Mutability:
- Consider using immutable collections like
VectororListfor functional programming practices. Use arrays when mutability is a necessity or for performance reasons.
- Consider using immutable collections like