-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTryDemo.scala
More file actions
95 lines (62 loc) · 2.65 KB
/
TryDemo.scala
File metadata and controls
95 lines (62 loc) · 2.65 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import scala.util.{Failure, Random, Success, Try, Using}
import scala.io.Source
import scala.collection.mutable
object TryDemo extends App{
/**
* Reads a file and returns a Map to simulate a database
* @param path Path of the file
* @return Map of users with its key as userid and value as a Tuple2 with its
* first element as name and second as age
*/
def readFile(path : String) : Map[Int,(String,Int)] = {
val userData = mutable.Map[Int, (String,Int)]()
Using.resource(Source.fromFile(path)){source =>
for (line <- source.getLines()) {
val userInfo = line.split(",")
userData.addOne(userInfo(0).toInt -> (userInfo(1),userInfo(2).toInt))
}
}
userData.toMap
}
def displayUserInfo(userId: Int, database: Map[Int, (String, Int)]): Try[String] =
Try(database(userId))
.flatMap(parseUserInfo)
.flatMap(formatUserInfo)
def parseUserInfo(userInfo : (String,Int)) : Try[(String,String,Int)] = {
val names = userInfo._1.split("_").map(_.capitalize)
if (names.length < 2) Failure(new Exception("Incorrect user name format"))
else Success(names(0),names(1),userInfo._2)
}
def formatUserInfo(details: (String, String, Int)): Try[String] =
if (details._3 < 0) Failure(new Exception("Age must be Positive"))
else Success(s"FirstName = ${details._1} ; LastName = ${details._2} ; Age = ${details._3}")
val database = readFile("specify the path of user_info.txt") // download user_info.txt
//test1
//User do not exist in the database
val test1 = displayUserInfo(25,database)
println(test1)
//test2
//user exist in the database
val test2 = displayUserInfo(20, database)
println(test2)
//test3
//user's age is negative
val test3 = displayUserInfo(19, database)
println(test3)
//test4
//user's name is in incorrect format
val test4 = displayUserInfo(4,database)
println(test4)
/*
Some key points from above example
1. We specified the return type of each method as Try[T] instead of just T.
This not only allows us to handle exceptions in a functional way but also
enables us to use the methods directly in flatMap as lambda expressions.
2. Each computation (like parsing or formatting) can be applied only
if the previous computation was successful.
3. If an error occurs at any point, it is automatically propagated as a Failure
to the final result without executing the remaining logic.
4. You don't need explicit error handling for each function call,
the chaining takes care of it, passing Success values to the next step or stopping with a Failure.
*/
}