Introduction to Scala Part3: Option & Pattern Matching
Bubu
4,429 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
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
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("theimp@CasterlyRock.we")),
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
Enter to Rename, Shift+Enter to Preview