Table of Contents
- Scala Array class introduction
- Important note about the Array examples
- Common Array uses
- Create a new Array with initial elements
- Create a new Array by populating it
- Multidimensional arrays
- How to add (append and prepend) elements to an Array
- Filtering methods (how to “remove” elements from an Array)
- How to “update” Array elements
- Transformer methods
- Informational and mathematical methods
- Grouping methods
- Looping over an Array with for and foreach
- A few things you can do with an Array of Options
- Scala Array summary
This page contains dozens of examples that show how to use the methods on the Scala Array class.
Scala Array class introduction
The Scala Array class is a mutable, indexed, sequential collection. Unlike the Scala ArrayBuffer class, the Array class is only mutable in the sense that its existing elements can be modified; it can’t be resized like ArrayBuffer.
If you’re coming to Scala from Java:
- You can think of the Scala
Array
as being a wrapper around the Javaarray
primitive type. - I rarely use
Array
; it’s okay to use it when you write OOP code, but if you’re writing multi-threaded or FP code, you won’t want to use it because it’s elements can be mutated. You should generally prefer the Scala Vector and ArrayBuffer classes rather than usingArray
.
Important note about the Array examples
In many of the examples that follow — specifically when I demonstrate many of the methods available on the Array
class, like map
, filter
, etc. — you need to assign the result of the operation shown to a new variable, like this:
val x = nums.distinct
In an effort to keep the examples smaller and easier to read, I generally don’t do that in the following examples. I generally show the result of the expression on the right side of the comments.
Common Array uses
I don’t normally use a Scala Array
, but one benefit of it is that you can update elements in place, as shown in these examples:
val nums = Array(1,2,3) // Array[Int] = Array(1, 2, 3)
# access elements by index
nums(0) // 1
nums(1) // 2
# update elements in place
nums(0) = 10 // Array(10, 2, 3)
nums.map(_ * 2) // Array(20, 4, 6)
nums.filter(_ < 3) // Array(2)
nums.indexOf(2) // 1
nums.size // 3
# multi-dimensional arrays
val rows = 2
val cols = 3
val a = Array.ofDim[String](rows, cols)
Create a new Array with initial elements
Create an Array
:
val nums = Array(1, 2, 3) // Array[Int] = Array(1, 2, 3)
val words = Array("foo", "bar") // Array[String] = Array(foo, bar)
When an array holds mixed data types
When the values in the sequence have mixed/multiple types you may want to specify the type of the sequence:
val x = Array(1, 1.0, 1F) // Array[Double] = Array(1.0, 1.0, 1.0)
val x: Array[Number] = Array(1, 1.0, 1F) // Array[Number] = Array(1, 1.0, 1.0)
A custom example:
trait Animal
trait Furry
case class Dog(name: String) extends Animal with Furry
case class Cat(name: String) extends Animal with Furry
# (a) resulting type is `Array[Product with Serializable with Animal with Furry]`
val animalHouse = Array(
Dog("Rover"),
Cat("Felix")
)
# (b) be clear you want `Array[Animal]`
val animalHouse: Array[Animal] = Array(
Dog("Rover"),
Cat("Felix")
)
How to create an empty Array
:
val nums = Array[Int]() // Array[Int] = Array()
Remember the constructor syntax is just syntactic sugar for apply
:
val nums = Array(1, 2, 3) // Array[Int] = Array(1, 2, 3)
val nums = Array.apply(1, 2, 3) // Array[Int] = Array(1, 2, 3)
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Create a new Array by populating it
You can create a new Array
that’s populated with initial elements using a Range
:
# to, until
(1 to 5).toArray // Array[Int] = Range 1 to 5
(1 until 5).toArray // Array[Int] = Range 1 to 5
(1 to 10 by 2).toArray // Array[Int] = inexact Range 1 to 10 by 2
(1 until 10 by 2).toArray // Array[Int] = inexact Range 1 until 10 by 2
(1 to 10).by(2).toArray // Array[Int] = inexact Range 1 to 10 by 2
('d' to 'h').toArray // Array[Char] = NumericRange d to h
('d' until 'h').toArray // Array[Char] = NumericRange d until h
('a' to 'f').by(2).toArray // Array[Char] = NumericRange a to f by ?
# range method
Array.range(1, 3) // Array[Int] = Array(1, 2)
Array.range(1, 6, 2) // Array[Int] = Array(1, 3, 5)
You can also use the fill
and tabulate
methods:
Array.fill(3)("foo") // Array[String] = Array(foo, foo, foo)
Array.tabulate(3)(n => n * n) // Array[Int] = Array(0, 1, 4)
Array.tabulate(4)(n => n * n) // Array[Int] = Array(0, 1, 4, 9)
Multidimensional arrays
Multidimensional arrays in Scala:
val rows = 2
val cols = 3
val a = Array.ofDim[String](rows, cols)
In the REPL:
scala> val a = Array.ofDim[String](rows, cols)
a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
Notice that a string array defaults to null values.
Add elements to the array:
a(0)(0) = "a"
a(0)(1) = "b"
a(0)(2) = "c"
a(1)(0) = "d"
a(1)(1) = "e"
a(1)(2) = "f"
The result in the REPL:
scala> a
res0: Array[Array[String]] = Array(Array(a, b, c), Array(d, e, f))
Access the elements using parentheses, similar to a one-dimensional array:
scala> val x = a(0)(0)
x: String = a
scala> val x = a(0)(1)
x: String = b
scala> val x = a(1)(0)
x: String = d
Iterate over the array with a for-loop:
for {
i <- 0 until rows
j <- 0 until cols
} println(s"($i)($j) = ${a(i)(j)}")
(0)(0) = a
(0)(1) = b
(0)(2) = c
(1)(0) = d
(1)(1) = e
(1)(2) = f
A three-dimensional array:
val x, y, z = 3
val a = Array.ofDim[Int](x,y,z)
for {
i <- 0 until x
j <- 0 until y
k <- 0 until z
} println(s"($i)($j)($k) = ${a(i)(j)(k)}")
# that prints:
(0)(0)(0) = 0
(0)(0)(1) = 0
(0)(0)(2) = 0
(0)(1)(0) = 0
(0)(1)(1) = 0
(0)(1)(2) = 0
...
...
How to use an array of arrays
Can also create an array of arrays:
scala> val a = Array( Array("a", "b", "c"), Array("d", "e", "f") )
a: Array[Array[String]] = Array(Array(a, b, c), Array(d, e, f))
scala> a(0)
res0: Array[String] = Array(a, b, c)
scala> a(0)(0)
res1: String = a
How to add (append and prepend) elements to an Array
You can’t resize a Scala Array
, but you can use these operators (methods) to append and prepend elements to an array while assigning the result to a new variable:
Method | Description | Example |
---|---|---|
:+ |
append 1 item | oldArray :+ e |
++ |
append N items | oldArray ++ newArray |
+: |
prepend 1 item | e +: oldArray |
++: |
prepend N items | newArray ++: oldArray |
Append and prepend examples
These examples show how to use those methods to append and prepend elements to an Array
:
val v1 = Array(4,5,6) // Array[Int] = Array(4, 5, 6)
val v2 = v1 :+ 7 // Array(4, 5, 6, 7)
val v3 = v2 ++ Array(8,9) // Array(4, 5, 6, 7, 8, 9)
val v4 = 3 +: v3 // Array(3, 4, 5, 6, 7, 8, 9)
val v5 = Array(1,2) ++: v4 // Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
About the :
character in the method names
Note that during these operations the :
character is always next to the old (original) sequence. I use that as a way to remember these methods.
The correct technical way to think about this is that a Scala method name that ends with the :
character is right-associative, meaning that the method comes from the variable on the right side of the expression. Therefore, with +:
and ++:
, these methods comes from the Array
that’s on the right of the method name.
Filtering methods (how to “remove” elements from an Array)
An Array
is an immutable sequence, so you don’t remove elements from it. Instead, you describe how to remove elements as you assign the results to a new collection. These methods let you “remove” elements during this process:
Method | Description |
---|---|
distinct |
Return a new sequence with no duplicate elements |
drop(n) |
Return all elements after the first n elements |
dropRight(n) |
Return all elements except the last n elements |
dropWhile(p) |
Drop the first sequence of elements that matches the predicate p |
filter(p) |
Return all elements that match the predicate p |
filterNot(p) |
Return all elements that do not match the predicate p |
find(p) |
Return the first element that matches the predicate p |
head |
Return the first element; can throw an exception if the Array is empty |
headOption |
Returns the first element as an Option |
init |
All elements except the last one |
intersect(s) |
Return the intersection of the sequence and another sequence s |
last |
The last element; can throw an exception if the Array is empty |
lastOption |
The last element as an Option |
slice(f,u) |
A sequence of elements from index f (from) to index u (until) |
tail |
All elements after the first element |
take(n) |
The first n elements |
takeRight(n) |
The last n elements |
takeWhile(p) |
The first subset of elements that matches the predicate p |
Examples
val a = Array(10, 20, 30, 40, 10) // Array(10, 20, 30, 40, 10)
a.distinct // Array(10, 20, 30, 40)
a.drop(2) // Array(30, 40, 10)
a.dropRight(2) // Array(10, 20, 30)
a.dropWhile(_ < 25) // Array(30, 40, 10)
a.filter(_ < 25) // Array(10, 20, 10)
a.filter(_ > 100) // Array()
a.filterNot(_ < 25) // Array(30, 40)
a.find(_ > 20) // Some(30)
a.head // 10
a.headOption // Some(10)
a.init // Array(10, 20, 30, 40)
a.intersect(Array(19,20,21)) // Array(20)
a.last // 10
a.lastOption // Some(10)
a.slice(2,4) // Array(30, 40)
a.tail // Array(20, 30, 40, 10)
a.take(3) // Array(10, 20, 30)
a.takeRight(2) // Array(40, 10)
a.takeWhile(_ < 30) // Array(10, 20)
As noted, head
and last
can throw exceptions:
scala> val a = Array[Int]()
a: Array[Int] = Array()
scala> a.head
java.lang.UnsupportedOperationException: empty.head
at scala.collection.immutable.Array.head(Array.scala:185)
... 28 elided
scala> a.last
java.lang.UnsupportedOperationException: empty.last
at scala.collection.immutable.Array.last(Array.scala:197)
... 28 elided
How to “update” Array elements
Because Array
is immutable, you can’t update elements in place, but depending on your definition of “update,” there are a variety of methods that let you update an Array
as you assign the result to a new variable:
Method | Returns |
---|---|
collect(pf) |
A new collection by applying the partial function pf to all elements of the sequence, returning elements for which the function is defined |
distinct |
A new sequence with no duplicate elements |
flatten |
Transforms a sequence of sequences into a single sequence |
flatMap(f) |
When working with sequences, it works like map followed by flatten |
map(f) |
Return a new sequence by applying the function f to each element in the Array |
updated(i,v) |
A new sequence with the element at index i replaced with the new value v |
union(s) |
A new sequence that contains elements from the current sequence and the sequence s |
val x = Array(Some(1), None, Some(3), None) // Array[Option[Int]] = Array(Some(1), None, Some(3), None)
x.collect{case Some(i) => i} // Array(1, 3)
val x = Array(1,2,1,2)
x.distinct // Array(1, 2)
x.map(_ * 2) // Array(2, 4, 2, 4)
x.updated(0,100) // Array(100, 2, 1, 2)
val a = Array(Array(1,2), Array(3,4))
a.flatten // Array(1, 2, 3, 4)
val fruits = Array("apple", "pear")
fruits.map(_.toUpperCase) // Array(APPLE, PEAR)
fruits.flatMap(_.toUpperCase) // Array(A, P, P, L, E, P, E, A, R)
Array(2,4).union(Array(1,3)) // Array(2, 4, 1, 3)
Transformer methods
Method | Returns |
---|---|
collect(pf) |
Creates a new collection by applying the partial function pf to all elements of the sequence, returning elements for which the function is defined |
diff(c) |
The difference between this sequence and the collection c |
distinct |
A new sequence with no duplicate elements |
flatten |
Transforms a sequence of sequences into a single sequence |
flatMap(f) |
When working with sequences, it works like map followed by flatten |
map(f) |
A new sequence by applying the function f to each element in the Array |
reverse |
A new sequence with the elements in reverse order |
sortWith(f) |
A new sequence with the elements sorted with the use of the function f |
updated(i,v) |
A new Array with the element at index i replaced with the new value v |
union(c) |
A new sequence that contains all elements of the sequence and the collection c |
zip(c) |
A collection of pairs by matching the sequence with the elements of the collection c |
zipWithIndex |
A sequence of each element contained in a tuple along with its index |
val x = Array(Some(1), None, Some(3), None)
x.collect{case Some(i) => i} // Array(1, 3)
# diff
val oneToFive = (1 to 5).toArray // Array(1, 2, 3, 4, 5)
val threeToSeven = (3 to 7).toArray // Array(3, 4, 5, 6, 7)
oneToFive.diff(threeToSeven) // Array(1, 2)
threeToSeven.diff(oneToFive) // Array(6, 7)
Array(1,2,1,2).distinct // Array(1, 2)
val a = Array(Array(1,2), Array(3,4))
a.flatten // Array(1, 2, 3, 4)
# map, flatMap
val fruits = Array("apple", "pear")
fruits.map(_.toUpperCase) // Array[String] = Array(APPLE, PEAR)
fruits.flatMap(_.toUpperCase) // Array[Char] = Array(A, P, P, L, E, P, E, A, R)
Array(1,2,3).reverse // Array(3, 2, 1)
val nums = Array(10, 5, 8, 1, 7)
nums.sorted // Array(1, 5, 7, 8, 10)
nums.sortWith(_ < _) // Array(1, 5, 7, 8, 10)
nums.sortWith(_ > _) // Array(10, 8, 7, 5, 1)
Array(1,2,3).updated(0,10) // Array(10, 2, 3)
Array(2,4).union(Array(1,3)) // Array(2, 4, 1, 3)
# zip
val women = Array("Wilma", "Betty") // Array(Wilma, Betty)
val men = Array("Fred", "Barney") // Array(Fred, Barney)
val couples = women.zip(men) // Array((Wilma,Fred), (Betty,Barney))
val a = ('a' to 'd').toArray // Array[Char] = Array(a, b, c, d)
a.zipWithIndex // Array((a,0), (b,1), (c,2), (d,3))
Scala Array.range quirk
A quirk about trying to create an array of characters with the Array.range method:
# works as expected
('a' to 'e').toArray // Array[Char] = Array(a, b, c, d, e)
# Array.range always returns Array[Int]
val a = Array.range('a', 'e') // Array[Int] = Array(97, 98, 99, 100)
Informational and mathematical methods
Method | Returns |
---|---|
contains(e) |
True if the sequence contains the element e |
containsSlice(s) |
True if the sequence contains the sequence s |
count(p) |
The number of elements in the sequence for which the predicate is true |
endsWith(s) |
True if the sequence ends with the sequence s |
exists(p) |
True if the predicate returns true for at least one element in the sequence |
find(p) |
The first element that matches the predicate p , returned as an Option |
forall(p) |
True if the predicate p is true for all elements in the sequence |
hasDefiniteSize |
True if the sequence has a finite size |
indexOf(e) |
The index of the first occurrence of the element e in the sequence |
indexOf(e,i) |
The index of the first occurrence of the element e in the sequence, searching only from the value of the start index i |
indexOfSlice(s) |
The index of the first occurrence of the sequence s in the sequence |
indexOfSlice(s,i) |
The index of the first occurrence of the sequence s in the sequence, searching only from the value of the start index i |
indexWhere(p) |
The index of the first element where the predicate p returns true |
indexWhere(p,i) |
The index of the first element where the predicate p returns true, searching only from the value of the start index i |
isDefinedAt(i) |
True if the sequence contains the index i |
isEmpty |
True if the sequence contains no elements |
lastIndexOf(e) |
The index of the last occurrence of the element e in the sequence |
lastIndexOf(e,i) |
The index of the last occurrence of the element e in the sequence, occurring before or at the index i |
lastIndexOfSlice(s) |
The index of the last occurrence of the sequence s in the sequence |
lastIndexOfSlice(s,i) |
The index of the last occurrence of the sequence s in the sequence, occurring before or at the index i |
lastIndexWhere(p) |
The index of the first element where the predicate p returns true |
lastIndexWhere(p,i) |
The index of the first element where the predicate p returns true, occurring before or at the index i |
max |
The largest element in the sequence |
min |
The smallest element in the sequence |
nonEmpty |
True if the sequence is not empty (i.e., if it contains 1 or more elements) |
product |
The result of multiplying the elements in the collection |
segmentLength(p,i) |
The length of the longest segment for which the predicate p is true, starting at the index i |
size |
The number of elements in the sequence |
startsWith(s) |
True if the sequence begins with the elements in the sequence s |
startsWith(s,i) |
True if the sequence has the sequence s starting at the index i |
sum |
The sum of the elements in the sequence |
fold(s)(o) |
“Fold” the elements of the sequence using the binary operator o , using an initial seed s (see also reduce ) |
foldLeft(s)(o) |
“Fold” the elements of the sequence using the binary operator o , using an initial seed s , going from left to right (see also reduceLeft ) |
foldRight(s)(o) |
“Fold” the elements of the sequence using the binary operator o , using an initial seed s , going from right to left (see also reduceRight ) |
reduce |
“Reduce” the elements of the sequence using the binary operator o |
reduceLeft |
“Reduce” the elements of the sequence using the binary operator o , going from left to right |
reduceRight |
“Reduce” the elements of the sequence using the binary operator o , going from right to left |
Examples
First, some sample data:
val evens = Array(2, 4, 6) // Array(2, 4, 6)
val odds = Array(1, 3, 5) // Array(1, 3, 5)
val fbb = "foo bar baz" // String = foo bar baz
val firstTen = (1 to 10).toArray // Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val fiveToFifteen = (5 to 15).toArray // Array(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
val empty = Array[Int]() // Array()
val letters = ('a' to 'f').toArray // Array(a, b, c, d, e, f)
The examples:
evens.contains(2) // true
firstTen.containsSlice(Array(3,4,5)) // true
firstTen.count(_ % 2 == 0) // 5
firstTen.endsWith(Array(9,10)) // true
firstTen.exists(_ > 10) // false
firstTen.find(_ > 2) // Some(3)
firstTen.forall(_ < 20) // true
firstTen.hasDefiniteSize // true
empty.hasDefiniteSize // true
letters.indexOf('b') // 1 (zero-based)
letters.indexOf('d', 2) // 3
letters.indexOf('d', 3) // 3
letters.indexOf('d', 4) // -1
letters.indexOfSlice(Array('c','d')) // 2
letters.indexOfSlice(Array('c','d'),2) // 2
letters.indexOfSlice(Array('c','d'),3) // -1
firstTen.indexWhere(_ == 3) // 2
firstTen.indexWhere(_ == 3, 2) // 2
firstTen.indexWhere(_ == 3, 5) // -1
letters.isDefinedAt(1) // true
letters.isDefinedAt(20) // false
letters.isEmpty // false
empty.isEmpty // true
# lastIndex...
val fbb = "foo bar baz"
fbb.indexOf('a') // 5
fbb.lastIndexOf('a') // 9
fbb.lastIndexOf('a', 10) // 9
fbb.lastIndexOf('a', 9) // 9
fbb.lastIndexOf('a', 6) // 5
fbb.lastIndexOf('a', 5) // 5
fbb.lastIndexOf('a', 4) // -1
fbb.lastIndexOfSlice("ar") // 5
fbb.lastIndexOfSlice(Array('a','r')) // 5
fbb.lastIndexOfSlice(Array('a','r'), 4) // -1
fbb.lastIndexOfSlice(Array('a','r'), 5) // 5
fbb.lastIndexOfSlice(Array('a','r'), 6) // 5
fbb.lastIndexWhere(_ == 'a') // 9
fbb.lastIndexWhere(_ == 'a', 4) // -1
fbb.lastIndexWhere(_ == 'a', 5) // 5
fbb.lastIndexWhere(_ == 'a', 6) // 5
fbb.lastIndexWhere(_ == 'a', 8) // 5
fbb.lastIndexWhere(_ == 'a', 9) // 9
firstTen.max // 10
letters.max // f
firstTen.min // 1
letters.min // a
letters.nonEmpty // true
empty.nonEmpty // false
firstTen.product // 3628800
letters.size // 6
val x = Array(1,2,9,1,1,1,1,4)
x.segmentLength(_ < 4, 0) // 2
x.segmentLength(_ < 4, 2) // 0
x.segmentLength(_ < 4, 3) // 4
x.segmentLength(_ < 4, 4) // 3
firstTen.startsWith(Array(1,2)) // true
firstTen.startsWith(Array(1,2), 0) // true
firstTen.startsWith(Array(1,2), 1) // false
firstTen.sum // 55
firstTen.fold(100)(_ + _) // 155
firstTen.foldLeft(100)(_ + _) // 155
firstTen.foldRight(100)(_ + _) // 155
firstTen.reduce(_ + _) // 55
firstTen.reduceLeft(_ + _) // 55
firstTen.reduceRight(_ + _) // 55
firstTen.fold(100)(_ - _) // 45
firstTen.foldLeft(100)(_ - _) // 45
firstTen.foldRight(100)(_ - _) // 95
firstTen.reduce(_ - _) // -53
firstTen.reduceLeft(_ - _) // -53
firstTen.reduceRight(_ - _) // -5
More information on fold and reduce
Grouping methods
Method | Returns |
---|---|
groupBy(f) |
A map of collections created by the function f |
grouped |
Breaks the sequence into fixed-size iterable collections |
partition(p) |
Two collections created by the predicate p |
sliding(i,s) |
Group elements into fixed size blocks by passing a sliding window of size i and step s over them |
span(p) |
A collection of two collections; the first created by sequence.takeWhile(p) , and the second created by sequence.dropWhile(p) |
splitAt(i) |
A collection of two collections by splitting the sequence at index i |
unzip |
The opposite of zip , breaks a collection into two collections by dividing each element into two pieces; such as breaking up a sequence of Tuple2 elements |
Examples
val firstTen = (1 to 10).toArray // Array(1,2,3,4,5,6,7,8,9,10)
firstTen.groupBy(_ > 5) // Map[Boolean,Array[Int]] = Map(false -> Array(1,2,3,4,5), true -> Array(6,7,8,9,10))
firstTen.grouped(2) // Iterator[Array[Int]] = non-empty iterator
firstTen.grouped(2).toArray // Array[Array[Int]] = Array(Array(1,2), Array(3,4), Array(5,6), Array(7,8), Array(9,10))
firstTen.grouped(5).toArray // Array[Array[Int]] = Array(Array(1,2,3,4,5), Array(6,7,8,9,10))
"foo bar baz".partition(_ < 'c') // (String, String) = (" ba ba",foorz) //Tuple2
firstTen.partition(_ > 5) // (Array[Int], Array[Int]) = (Array(6,7,8,9,10),Array(1,2,3,4,5)) //Tuple2
firstTen.sliding(2) // Array[Int]] = non-empty iterator
firstTen.sliding(2).toArray // Array[Array[Int]] = Array(Array(1,2), Array(2,3), Array(3,4), Array(4,5), Array(5,6), Array(6,7), Array(7,8), Array(8,9), Array(9,10))
firstTen.sliding(2,2).toArray // Array[Array[Int]] = Array(Array(1,2), Array(3,4), Array(5,6), Array(7,8), Array(9,10))
firstTen.sliding(2,3).toArray // Array[Array[Int]] = Array(Array(1,2), Array(4,5), Array(7,8), Array(10))
firstTen.sliding(2,4).toArray // Array[Array[Int]] = Array(Array(1,2), Array(5,6), Array(9,10))
val x = Array(15, 10, 5, 8, 20, 12)
x.groupBy(_ > 10) // Map[Boolean,Array[Int]] = Map(false -> Array(10, 5, 8), true -> Array(15, 20, 12))
x.partition(_ > 10) // (Array(15, 20, 12),Array(10, 5, 8))
x.span(_ < 20) // (Array(15, 10, 5, 8),Array(20, 12))
x.splitAt(2) // (Array(15, 10),Array(5, 8, 20, 12))
More information:
Looping over an Array
with for and foreach
val oneToFive = Array(1,2,3,4,5) // Array(1, 2, 3, 4, 5)
for (i <- oneToFive) yield i // Array(1, 2, 3, 4, 5)
for (i <- oneToFive) yield i * 2 // Array(2, 4, 6, 8, 10)
for (i <- oneToFive) yield i % 2 // Array(1, 0, 1, 0, 1)
for { // Array(3, 4, 5)
i <- oneToFive
if i > 2
} yield i
for { // Array(6, 8, 10)
i <- oneToFive
if i > 2
} yield {
// could be multiple lines here
i * 2
}
# foreach (use for side effects)
val oneToThree = Array(1, 2, 3)
oneToThree.foreach(print) // 123
for (i <- oneToThree) print(i) // 123
A few things you can do with an Array of Options
val x = Array(Some(1), None, Some(3), None) // Array[Option[Int]] = Array(Some(1), None, Some(3), None)
x.flatten // Array(1, 3)
x.collect{case Some(i) => i} // Array(1, 3)
# map, flatten, flatMap
import scala.util.Try
def toInt(s: String): Option[Int] = Try(Integer.parseInt(s)).toOption
val strings = Array("1", "2", "foo", "3", "bar")
strings.map(toInt) // Array(Some(1), Some(2), None, Some(3), None)
strings.map(toInt).flatten // Array(1, 2, 3)
strings.flatMap(toInt) // Array(1, 2, 3)
Scala Array summary
In summary, I hope these Array
examples are helpful. If I made a mistake, or you know another way to do something with an Array
I haven’t shown, leave a note in the Comments section.