-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPatternmatchObject2.scala
44 lines (37 loc) · 1.43 KB
/
PatternmatchObject2.scala
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
package ScalaBasic
// https://www.youtube.com/watch?v=k0Oz8RhsWYI&list=PLmOn9nNkQxJEqCNXBu5ozT_26xwvUbHyE&index=154
object PatternmatchObject2 extends App {
// run
val namesString = "Alice,Ken,Amy"
val namesString2 = "Alice,Ken,Amy,Yuri"
namesString match{
// in here, Names(first, second, third) will call Names' unapply method
// -> if return some (pattern match success), will give result to first, second, third
// -> if return none -> pattern match failed
// note : if case objectCollector ( Names(first, second, third)) has multiple arguments -> will call unapplySeq by default
case Names(first, second, third) => {
println("the string contains 3 names, pattern match OK! ")
println(s"$first, $second, $third")
}
case _ => println("nothing matched !")
}
namesString2 match{
case Names(first, second, third) => {
println("the string contains 3 names")
println(s"$first, $second, $third")
}
case _ => println("nothing matched !")
}
}
object Names {
// if pattern match success -> return Some, else return None
// Option[Seq[String]] : accept MULTIPLE inputs (multiple string in Seq)
// +A => List[String] transform to List[Any]
// -A => List[Any] transform to List[String]
// A => nothing transformed, the default case we use
def unapplySeq(str: String): Option[Seq[String]] = {
if (str.contains(",")) {
Some(str.split(","))
} else None
}
}