-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtry.sc
More file actions
42 lines (35 loc) · 747 Bytes
/
try.sc
File metadata and controls
42 lines (35 loc) · 747 Bytes
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
import scala.util.Try
// we can iterate directly over successful Try values
for {
x <- Try(5)
y <- Try(6)
z <- Try(y + 2)
} println(x + y + z)
// or keep them for further computations
val q = for {
x <- Try(5)
y <- Try(6)
z <- Try(y + 2)
} yield x + y + z
assert { q.isSuccess }
// such as converting them to a (nonempty) option
assert { q.toOption.map(_ + 1) == Some(20) }
// a failure in one or more of the Try values leads to an empty iteration
for {
x <- Try(5)
y <- Try {
6 / 0
}
z <- Try(y + 2)
} println(x + y + z)
val r = for {
x <- Try(5)
y <- Try {
6 / 0
}
z <- Try(y + 2)
} yield(x + y + z)
assert { r.isFailure }
// and an empty option
assert { r.toOption.map(_ + 1) == None }
println("■")