1+ package s4j .scala .chapter20
2+
3+ import s4j .scala .chapter20 .CustomerDatabase .database
4+
5+ object CustomerDatabase {
6+ val database = Customers ()
7+
8+ val customerA = Customer (" Albert" , Some (Address (" 1a Bridge St" , None )))
9+ val customerB = Customer (" Beatriz" , None )
10+ val customerC = Customer (" Carol" , Some (Address (" 2a Finsbury Circus" , Some (" AL1 2PY" ))))
11+ val customerD = Customer (" Sherlock" , Some (Address (" 21b Baker Street" , Some (" NW1 6XE" ))))
12+
13+ customerA.add(PricedItem (10 ))
14+ customerA.add(PricedItem (5 ))
15+ customerC.add(PricedItem (10 ))
16+
17+ database.add(customerA)
18+ database.add(customerB)
19+ database.add(customerC)
20+ database.add(customerD)
21+ }
22+
23+ object Example extends App {
24+
25+ // null case
26+ val albert = database.findOrNull(" Albert" )
27+ val basket = if (albert != null ) albert.total else 0D
28+
29+ // map over option
30+ val exists = database.find(" Albert" ).map(customer => " customer exists" )
31+ val basketValue = database.find(" Albert" ).map(customer => customer.total).getOrElse(0D ) // forced to handle the else? get would throw
32+
33+
34+ val customers = Set (" Albert" , " Beatriz" , " Carol" , " Dave" , " Erin" , " Sherlock" )
35+
36+ def sumCustomerBaskets_NulLCheckVersion () = {
37+ // all.map(customers.findOrNull).map(_.total).sum // throws NPE
38+ // or
39+ customers.map(database.findOrNull).map(customer => if (customer != null ) customer.total else 0D ).sum
40+ }
41+
42+ def sumCustomerBaskets_NulLAvoidingPatternMatch () = {
43+ customers.map(database.findOrNull(_) match {
44+ case customer@ Customer (_, _) => customer.total // why no if customer != null clause? it matches on null below
45+ case a @ _ => println(a); 0D
46+ }).sum
47+ }
48+
49+ def sumCustomerBaskets_MapCouldThrowAnException () = {
50+ // all.map(customers.find(_)).map(customer => customer.get.total) // could throw an exception
51+ // customers.find("Missing").map(customer => customer.total).get // throws an exception
52+ database.find(" Missing" ) match {
53+ case Some (customer) => customer.total
54+ case None => 0D
55+ }
56+ }
57+
58+ def sumCustomerBaskets_MapThenFlattenVersion () = {
59+ customers.map(database.find(_).map(_.total)).flatten.sum
60+ }
61+
62+ def sumCustomerBaskets_FlatMapVersion () = {
63+ customers.flatMap(name => database.find(name)).map(customer => customer.total).sum
64+ }
65+
66+
67+ val partial : Set [Option [Customer ]] = customers.map(database.find)
68+
69+ println(" 1. " + sumCustomerBaskets_NulLCheckVersion())
70+ println(" 2. " + sumCustomerBaskets_NulLAvoidingPatternMatch()) // yuk!
71+ println(" 3. " + sumCustomerBaskets_MapCouldThrowAnException())
72+ println(" 4. " + sumCustomerBaskets_MapThenFlattenVersion())
73+ println(" 5. " + sumCustomerBaskets_FlatMapVersion())
74+
75+ }
0 commit comments