array in scala

Arrays in Scala

In Scala, an array is a fixed-size, mutable collection of elements of the same type. Here's how you can create and work with arrays in Scala:

Creating an Array

To create an array in Scala, you can use the Array class and specify the type of elements the array will hold. Here's an example of creating an array of integers:

val numbers: Array[Int] = Array(1, 2, 3, 4, 5)
Accessing Elements

You can access elements in an array using their index. The index starts from 0 for the first element and goes up to array.length - 1 for the last element. Here's an example:

val firstElement: Int = numbers(0) // Accessing the first element
val thirdElement: Int = numbers(2) // Accessing the third element
Modifying Elements

You can modify elements in an array by assigning a new value to the desired index. Here's an example:

numbers(1) = 10 // Modifying the second element to be 10
Array Length

You can get the length of an array using the length property. Here's an example:

val length: Int = numbers.length // Getting the length of the array
Iterating Over an Array

You can iterate over the elements of an array using a loop or higher-order functions like foreach. Here's an example using a loop:

for (number <- numbers) {
  println(number) // Printing each element
}
Array Operations

Scala provides various array operations, such as sorting, filtering, mapping, and reducing. These operations can be performed using higher-order functions like map, filter, reduce, etc. Here's an example of sorting an array:

val sortedArray: Array[Int] = numbers.sorted // Sorting the array

Note: The examples provided here are just a few basic operations on arrays in Scala. There are many more operations and features available for working with arrays in Scala.