class Person //scala中定义一个类,只要class 类名 即可。caseclass Teacher(name:String, subject:String)extends Person
caseclass Student(name:String, classname:String)extends Person
caseclass Worker(name:String, work:String)extends Person
caseclass Stranger(name:String, age:Int)extends Person
def match6(p: Person):Unit= p match{//如果我们不确定输入参数的类型,那就把基类写上去。case Teacher("zs","yuwen")=>println("zs教语文")case Teacher("zs",subject)=>println("zs老师的科目为"+subject)case Teacher(name,subject)=>println("只要是Teacher类型且不满足上面两个case就输出这个")case p1:Teacher=>println(p1.name+"老师您好"+p1.subject)case p2:Student =>println(p2.name+"学生您好"+p2.classname)case p3:Worker if p3.work=="repair"=>println(p3.work+"先生您好")case p4:Worker =>println(p4.work+"普通工人")case _=>println("陌生人")}
Option与模式匹配/Some()/None
val map=Map("zs"->"a","ls"->"b","ww"->"c")def match7(name:String):Unit={var score=map.get(name)
score match{case Some(score)=>println(name+"的成绩为:"+score)case None=>println("查询不到"+name+"对应的成绩")}}
调用代码
object Test1 {def main(args: Array[String]):Unit={// match1("D")// match2("F",22)// match3("D","zhu")
match4(new FileNotFoundException())//因为异常都是类,// 而我们调用一个函数要输入的是对象,是实例,是实际的值//所以需要new一下创建一个对象。// var arr1 = Array("KB09", "KB07", "KB05", "KB02") //hello KB09*// var arr2 = Array("KB09") //hello KB09// var arr3 = Array("KB09", "KB07", "KB05") //hello,KB09andKB07andKB05// var arr4 = Array("KB02", "KB07", "KB05", "KB09") //who are you// match5(arr4)
match6(Teacher("zs","wen"))// match6(Stranger("zhu",14))
match7("zs")}}
隐式参数
含有隐式参数的函数可以不在object内,可以在一个类内,然后调用时创建类对象调用函数即可
但是隐式参数的定义必须在object内
在object内创建类对象时,会把这个类内函数,方法等都传进域内,从而起效果
这个时候要满足同一个类型只能有一个隐式参数定义
class Person
class Son extends Person{def fun(a:Int,b:Int)(Implicit c:Int,msg:String="hello"):Int={
println(msg)
a+b+c
}}object Test1{implicitval a:Int=10implicitval str:String="welcome"def main(args:Array[String]):Unit={val son=new Son //类Son中的方法,函数等都传进Test1域中val sum=son.fun(10,20)
println(sum)}}