Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
Arrays in Scala are mutable, fixed-size collections that allow you to store elements of the same type. They provide fast random access to elements based on their indices. Scala arrays are interoperable with Java arrays, and under the hood, a Scala Array is represented as a Java array.
Let's delve deeper into Scala arrays:
To create an array in Scala, you can use the Array
companion object:
val numbers = Array(1, 2, 3, 4, 5) val strings = Array("a", "b", "c")
To create an array of a specific size (with default values):
val fiveInts = new Array[Int](5) // Array(0, 0, 0, 0, 0) val fiveStrings = new Array[String](5) // Array(null, null, null, null, null)
Arrays are 0-indexed. You can access and modify elements using the index:
println(numbers(0)) // Prints 1 numbers(0) = 10 println(numbers(0)) // Prints 10
You can use a for loop or other higher-order functions to iterate over an array:
for (num <- numbers) println(num) numbers.foreach(println)
length: Get the number of elements in the array.
println(numbers.length) // 5
map: Transform each element of the array.
val squared = numbers.map(x => x * x)
filter: Get elements that satisfy a condition.
val evens = numbers.filter(_ % 2 == 0)
sorted: Returns a new array with elements sorted.
val sortedNumbers = numbers.sorted
mkString: Convert the array to a string with a custom separator.
println(numbers.mkString(", ")) // 10, 2, 3, 4, 5
Scala supports multi-dimensional arrays:
val matrix = Array.ofDim[Int](3, 3) // 3x3 matrix matrix(0)(0) = 1
To use certain array functions like sum
, min
, and max
, you might need to import them:
import scala.runtime.ScalaRunTime._ println(numbers.sum) // 24 println(numbers.min) // 2 println(numbers.max) // 10
Scala arrays can be seamlessly passed to Java methods that expect Java arrays and vice versa.
Arrays in Scala are a basic data structure, and they offer fast access and modification times. However, being mutable, they should be used with caution, especially in a multi-threaded environment. In many cases, you might find it beneficial to use other collections (like List
, Vector
, etc.) that offer more flexibility or immutability.
Creating and Initializing Arrays in Scala:
You can create and initialize arrays using the Array
class in Scala.
// Creating an array of integers val numbers: Array[Int] = Array(1, 2, 3, 4, 5) // Creating an array of strings val fruits: Array[String] = Array("Apple", "Banana", "Orange")
Accessing and Modifying Array Elements in Scala:
Array elements can be accessed using their index, and you can modify them as arrays are mutable.
// Accessing elements val firstNumber: Int = numbers(0) // Modifying elements numbers(1) = 10
Multidimensional Arrays in Scala:
Scala supports multidimensional arrays, allowing you to create arrays of arrays.
// Creating a 2D array val matrix: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
Iterating Over Arrays in Scala:
You can iterate over array elements using loops or higher-order functions like foreach
.
// Using a for loop for (number <- numbers) { println(number) } // Using foreach fruits.foreach(fruit => println(fruit))
Common Array Operations and Methods in Scala:
Arrays provide various methods for common operations like filtering, mapping, and finding elements.
// Filtering elements val evenNumbers: Array[Int] = numbers.filter(_ % 2 == 0) // Mapping elements val squaredNumbers: Array[Int] = numbers.map(num => num * num) // Finding elements val index: Int = numbers.indexOf(3)
Immutable Arrays in Scala with 'val':
While the content of arrays is mutable, you can use val
to make the array reference immutable.
val immutableArray: Array[Int] = Array(1, 2, 3) // This will result in a compilation error: // immutableArray = Array(4, 5, 6)
The val
keyword makes the reference to the array immutable, not the array's content.
Converting Arrays to Other Collections in Scala:
You can convert arrays to other collection types like List
, Seq
, or Vector
for increased flexibility.
val list: List[Int] = numbers.toList val seq: Seq[Int] = numbers.toSeq val vector: Vector[Int] = numbers.toVector
These conversions allow you to use array elements in a more functional programming style.