Introduction to Scala Part3: Option & Pattern Matching
Bubu
3,347 views
Methods of Option
get
Some(1).get // 1
None.get //java.util.NoSuchElementException: None.get
getOrElse
Some(1).getOrElse(2) // 1
None.getOrElse(2) // 2
Option
Option(1) // Some(1)
Option(null) // None
IsEmpty
Some(1).isEmpty // false
None.isEmpty // true
getNameOfPerson
getNameUsingMap
getEmail
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package fp101.tp03.option
object ExerciceOptionPerson {
/**
*
* email is not mandatory
*
*/
class Person(val name: String, val age: Int, val email: Option[String]) {
override def toString = s"Person($name, $age, $email)"
}
object Person { def apply(name: String, age: Int, email: Option[String]) = new Person(name, age, email) }
object PersonDao {
private val persons = Map(
1 -> Person("John Snow", 25, Some("john.snow@winterfell.we")),
2 -> Person("Tyrion Lannister", 30, Some("th[email protected]")),
3 -> Person("Sandor Clegane", 40, None))
def findById(id: Int): Option[Person] = persons.get(id)
def findAll = persons.values
}
/**
*
* return the name of p otherwise "N/A"
* using only if, else and Option methods
*/
def getName(p: Option[Person]): String = ???
/**
* Write the same function that bellow using only map and getOrElse
*/
def getNameUsingMap(p: Option[Person]): String = ???
/**