basic
package PatternMatch
object patternmatch {
println("Welcome to the Scala worksheet")
val data =2
data match {
case 1 => println("First")
case 2 => println("Second")
case _ => println("Not Known Number")
}
val result = data match {
case i if i == 1 => "The First"
case number if number ==2 => "The Second" + number
case _ => "Not Known Number"
}
println(result)
"Spark !" foreach { c => println (
c match {
case ' ' => "space"
case ch => "Char: " + ch
}
)}
def match_type(t : Any) = t match {
case p : Int => println("It is Integer")
case p : String => println("It is String, the content is : " + p)
case m: Map[_, _] => m.foreach(println)
case _ => println("Unknown type!!!")
}
match_type(2)
match_type("Spark")
match_type(Map("Scala" -> "Spark"))
def match_array(arr : Any) = arr match {
case Array(0) => println("Array:" + "0")
case Array(x, y) => println("Array:" + x + " " +y)
case Array(0, _*) => println("Array:" + "0 ...")
case _ => println("something else")
}
match_array(Array(0))
match_array(Array(0,1))
match_array(Array(0,1,2,3,4,5))
def match_list(lst : Any) = lst match {
case 0 :: Nil => println("List:" + "0")
case x :: y :: Nil => println("List:" + x + " " + y)
case 0 :: tail => println("List:" + "0 ...")
case _ => println("something else")
}
match_list(List(0))
match_list(List(3,4))
match_list(List(0,1,2,3,4,5))
def match_tuple(tuple : Any) = tuple match {
case (0, _) => println("Tuple:" + "0")
case (x, 0) => println("Tuple:" + x )
case _ => println("something else")
}
match_tuple((0,"Scala"))
match_tuple((2,0))
match_tuple((0,1,2,3,4,5))
}
提取器
package PatternMatch
object extrator {
println("Welcome to the Scala worksheet")
def match_array(arr : Any) = arr match {
case Array(0) => println("Array:" + "0")
case Array(x, y) => println("Array:" + x + " " +y)
case Array(0, _*) => println("Array:" + "0 ...")
case _ => println("something else")
}
match_array(Array(0))
match_array(Array(0,1))
match_array(Array(0,1,2,3,4,5))
val pattern = "([0-9]+) ([a-z]+)".r
"20150628 hadoop" match {
case pattern(num, item) => println(num + " : " + item)
}
}
case class
package PatternMatch
object casecalss {
println("Welcome to the Scala worksheet")
abstract class Person
case class Student(age: Int) extends Person
case class Worker(age: Int, salary: Double) extends Person
case object Shared extends Person
def caseOps(person: Person) = person match {
case Student(age) => println("I am " + age + "years old")
case Worker(_, salary) => println("Wow, I got " + salary)
case Shared => println("No property")
}
caseOps(Student(19))
caseOps(Shared)
val worker = Worker(29, 10000.1)
val worker2 = worker.copy(salary = 19.95)
val worker3 = worker.copy(age = 30)
val scores = Map("Alice" -> 99, "Spark" -> 100)
scores.get("Spark") match {
case Some(score) => println(score)
case None => println("No score")
}
}