模式匹配:
一个模式匹配包含了一系列备选项,每个都开始于关键字 case
def main(args: Array[String]) { print(1); } //模式匹配 def fun(x:Int):String = x match{ case 1 => "one" case 2 => "two" case _ => "many" }
Any代表任何类型: def main(args: Array[String]) { print(fun("two")); }
//模式匹配 def fun(x:Any):Any = x match{ case 1 => "one" case "two" => 2 case _ => "many" } |
If判断
//模式匹配 def bigData(data1:String): Unit = data1 match { case "Spark" => println("this is Spark") case _ if data1 == "Scala" => println("this is Scala") 也可写出:case data if data == "Scala" => println("this is Scala") 定义个变量data,将data1 绑定到data上 case _ => println("Others") }
|
类型匹配:
object Test{ def main(args: Array[String]) { val stu = new Student matchType(stu) // Student:xiaoming } //类匹配 def matchType(p:Person): Unit ={ p match { case stu:Student => println("Student:"+stu.name) case worker:Worker => println("Worker:"+worker) case _ => println("Others") } } }
class Person
class Student extends Person{ val name = "xiaoming" } class Worker extends Person{ val name = "xiaowang" }
|
object Test{ def main(args: Array[String]) { val alice = new Person("Alice",23) val bob = new Person("Bob",22) for(p<-List(alice,bob)) { p match { case Person("Alice",23) => println("Alice is 23 years old"); case Person("Bob",22) => println("Bob is 22 years old"); } } } } case class Person(name:String,age:Int) |
隐式转换:
object Test{ implicit val name:String = "scala" def main(args: Array[String]) { hiScala("aa") hiScala } def hiScala(implicit str:String){ println("str:"+str) } } //str:aa str:scala 什么都不传就传 隐式的scala |