scala(偏函数、部分函数、模式匹配、面向对象oop)
一、偏函数
偏函数是只对函数定义域的一个子集进行定义的函数
PartialFunction[-A,+B]是一个特质
A为函数定义域,B为偏函数返回值类型
apply()
isDefinedAt()
偏函数,传入一个String,返回一个Int
def funPartiton: PartialFunction[String, Int] = {
case "helle" => 1
case "world" => 0
case _ => 3
}
val i = funPartiton("kb11")
println(i)
def funPart2:PartialFunction[Int,String]={
case 1=>"优秀"
case 2=>"良好"
case 3=>"合格"
case _=>"渣渣"
}
println(funPart2(4))
val arr = Array(1,2,3,4)
val strings = arr.collect(funPart2)
def fun3:PartialFunction[String,Any]={
case "man" => 1
case "wowan" => 0
case _=> "不合法输入"
}
val arrs = Array("man","wowan","ww")
arrs.collect(fun3).foreach(println)
二、部分函数
def showMsg(title: String, content: String, height: Double) = {
println(title + " " + content + " " + height)
}
常规调用方法:
showMsg("警告", "当前河床水位线:", 19.8)
部分函数:
val title:String = "警告"
def showAlarm = showMsg(title,_:String,_:Double)
showAlarm("部分函数 当前河床水位线:", 19.8)
val content:String = "部分函数2 当前河床水位线:"
def showAlarm2 = showMsg(title,content,_:Double)
showAlarm2(19.8)
三、模式匹配
(1)基本模式匹配
def match1(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
def fun(x:Any): Unit = {
x match {
case x : Int => println("int型")
case x : String => println("string型")
case x : Double => println("Double型")
}
}
println(fun(10))
println(fun(3.5))
(2)模式守卫(在模式后加if)
def match2(x:Int):String=x match