Post

Scala: Collection and Chaining Functions

A comprehensive guide to Scala collections including Option, List, and Map with examples of map, flatten, and flatMap operations.

Scala: Collection and Chaining Functions
ItemVersion
Scala2.12.17
1
2
3
4
5
6
7
8
9
10
// Helper Functions
val tripleOption: Option[Int] => Option[Int] = {
  case Some(x) => Some(x * 3)
  case None => None
}

val tripleIterable: Option[Int] => Iterable[Int] = {
  case Some(x) => Some(x * 3)
  case None => None
}

1. Option

1.1. get

1
2
3
Some(10).get // 10
// println(noneValue.get) // throws NoSuchElementException
None.orElse(None).getOrElse(11) // 11

1.2. flatten

1
2
3
4
Some(Some(10)).flatten // Some(10)
Some(Some(None)).flatten // Some(None)
Some(None).flatten // None
None.flatten // None

1.3. map

1
2
Some(10).map(_ * 2) // Some(20)
(None: Option[Int]).map(_ * 2) // None

1.4. flatMap

1
2
Some(Some(10)).flatMap(tripleOption) // Some(30)
Some(None).flatMap(tripleOption) // None

1.5. exists

1
2
Some(10).exists(_ > 2) // true
(None: Option[Int]).exists(_ > 2) // None // always returns false

1.6. toList

1
2
Some(10).toList // List(10)
None.toList // List()

2. List

2.1. map

1
2
List(1, 2).map(_ * 2) // List(2, 4)
List(Option(1), None).map(tripleOption) // List(Some(3), None)

2.2. map, flatten, and flatMap

1
2
3
4
5
List(1, 2).map(_ * 2) // List(2, 4)
List(Some(1), Some(2), None).map(tripleOption) // List(Some(3), Some(6), None)
List(Some(1), Some(2), None).flatten // List(1, 2)
List(Some(1), Some(2), None).map(tripleOption).flatten // List(3, 6)
List(Some(1), Some(2), None).flatMap(tripleIterable) // List(3, 6) // flatMap == map + flatten

2.3. exists

1
2
List(1, 2).exists(_ == 2) // true
List(1, 2).exists(_ == 3) // false

3. Map

3.1. get

1
2
3
4
val numberWords = Map(1 -> "one", 2 -> "two", 3 -> "three")
numberWords.get(1) // Some(one)
numberWords.get(4) // None
numberWords.getOrElse(4, "four") // four
This post is licensed under CC BY 4.0 by the author.