-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20_monads.sc
65 lines (49 loc) · 1.1 KB
/
20_monads.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
57
58
59
60
61
62
63
64
65
//
//
//
//
import scala.util._
println("Welcome to the Scala Monads")
// A monad is defined in the wikibook, and in Wikipedia, as having three parts:
// 1. A type constructor
// 2. A unit function, commonly called return in Haskell [apply(...) in Scala]
// 3. A binding operation, commonly called >>= in Haskell [map(...) or flatMap(...) in Scala]
//
// OPTION
// //////////////
Option.apply("string").map { s => println(s) }
Option("String") map println
Option[String](null).map { s => s.length }
def printString(in: String): String = {
println(in);
in
}
Option("String") map printString
//
// handling null
// ////////////////
val npe: String = null
val better: Option[String] = Option(npe)
val some = Option("foo")
var foo = npe
if (foo == null) {
foo = "default"
}
println(foo)
better.getOrElse("default")
Option("foo").getOrElse("default")
//
// TRY
// //////////
val happyPath = Try[String]("Foo")
happyPath.isSuccess
val result = happyPath.get
val exCaught = Try(npe.toString)
exCaught.map { f => println("") }
exCaught.isFailure
exCaught.failed
val myEx = exCaught.failed.get
//
//
//
//