|
val partialFunction : PartialFunction[List[Int],String] = {
case 10::_ => "head is 10"
case x::12::_ => "mid is 12"
case x::y::_ => y.toString //如何判断位置不定的中间某个值
case g ::_ if g == 2=>"head is g==2" //加条件判断
case g ::_ if g == 1=>"head is g==1"
case _ => "unknow List"
}
//上面 val partialFunction : PartialFunction[List[Int],String] = {...}
//其中大括号中内容就会被编译器解释成:
//new PartialFunction[List[Int],String] = {// def apply(xs: List[Int]) = xs match {
// case 10::_ => "head is 10"
// case x::12::_ => "mid is 12"
// case x::y::_ => y.toString //如何判断位置不定的中间某个值
// case g ::_ if g == 2=>"head is g==2"
// case g ::_ if g == 1=>"head is g==1"
// case _ => "unknow List"
// }
// def isDefinedAt(xs: List[Int] = xs match {
// case 10::_ => true
// case x::12::_ => true
// case g ::_ if g == 2=>true
// case g ::_ if g == 1=>true
// case x::y::_ => true
// case _ => true //所以偏函数应用的时候最好不要将所有匹配都有,只能是你需要的才放进去,否则所有匹配你都要处理
// }
val r = partialFunction(List(10,12,13,18))
println(r)
val r1 = partialFunction(List(1,12,13,18))
println(r1)
val r2 = partialFunction(List(101,112,13,18))
println(r2)
val r3 = partialFunction(List(1))
println(r3)
显示如下:
head is 10
mid is 12
112
head is g==1
|
|