部分函数
object Test1 {
def main(args: Array[String]): Unit = {
def showMsg(title:String,content:String,num:Int):Unit={
println(title+":"+content+" "+num+" 米")
}
showMsg("警告","当前水位是",12)
val title="注意"
def showWaterAlter=showMsg(title,_:String,_:Int)
showWaterAlter("当前水位",14)
def add1(a:Int,b:Int,c:Int):Int={
a+b+c
}
println(add1(1,2,3))
val a=10
def add2=add1(_:Int,a,_:Int)
println(add2(2,3))
}
}
偏函数
object Test2 {
def main(args: Array[String]): Unit = {
def funPartional:PartialFunction[String,Int]={
case "hello"=>1
case "world"=>2
case _=>0
}
val worlds=List("hello","world","gree","kb09")
worlds.collect(funPartional).foreach(println)
for (elem <- worlds.collect(funPartional)) {println(elem)}
def par1:PartialFunction[String,Int]={
case "man" =>1
case "woman"=>2
case "male"=>1
case "female"=>2
case "男"=>1
case "女"=>2
case "gg"=>1
case "mm"=>2
case _=>0
}
val sex=List("man","woman","male","female")
sex.collect(par1).foreach(println)
def funTupple:PartialFunction[Char,(Char,Int)]={
case 'A'=>('A',1)
case 'B'=>('B',1)
case _ =>('X',1)
}
val tuple:(Char,Int)=funTupple('A')
println(tuple)
var chars=List('A','B','C','D')
val tuples:List[(Char,Int)]=chars.collect(funTupple)
tuples.foreach(println)
tuples.foreach(x=>{println(x._1)})
def fun2:PartialFunction[Any,Int]={
case i:Int=>i
case _=>0
}
var list=List("a",'c',2,2.5,4,6)
list.collect(fun2).foreach(println)
}
}