-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoption.sc
56 lines (48 loc) · 1.05 KB
/
option.sc
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// rename upon import
import collection.mutable.{Map => MMap}
val m2 = MMap("asdf" -> 3)
// continue with immutable maps (default)
val m = Map("hello" -> 7, "world" -> 9)
m("hello")
try {
m("hello")
} catch {
case _: Throwable => 8
}
m.get("hello")
m.get("world")
Some(7)
None
Some(7): Option[Int]
None: Option[Int]
// pattern matching
m.get("hello") match {
case None => println("nope")
case Some(v) => println("found value " + v)
}
m.get("world") match {
case None => println("nope")
case Some(v) => println("found value " + v)
}
// print sum if both lookups succeed
// gets unwieldy with more than two steps!
m.get("hello") match {
case None => println("nope")
case Some(v) =>
m.get("world") match {
case None => println("nope")
case Some(w) => println("the sum is " + (v + w))
}
}
// for comprehension
val z = for {
z <- Seq(5)
v1 <- m.get("hello")
v2 <- m.get("hello")
v3 <- m.get("hello")
v4 <- m.get("hello")
v5 <- m.get("hello")
w <- m.get("world")
} yield (v1 + v2 + v3 + v4 + v5 + w)
println(z)
println("■")