<Zhuuu_ZZ>Scala(七)部分函数&偏函数

部分函数

//部分函数
object Test1 {
  def main(args: Array[String]): Unit = {
    def showMsg(title:String,content:String,num:Int):Unit={
     println(title+":"+content+" "+num+" 米")
    }
    showMsg("警告","当前水位是",12)  //警告:当前水位是 12 米

    val title="注意"   //定义一个常量以便在大数据量时不用修改,可以少输入一个值。
    def showWaterAlter=showMsg(title,_:String,_:Int)//部分函数,参数类型顺序要和showMsg匹配,用_代替变量
    showWaterAlter("当前水位",14)  //注意:当前水位 14 米

    def add1(a:Int,b:Int,c:Int):Int={
      a+b+c
    }
    println(add1(1,2,3))  //6
    val a=10
    def add2=add1(_:Int,a,_:Int)
    println(add2(2,3))  //15
  }
}

偏函数

//偏函数
object Test2 {
  def main(args: Array[String]): Unit = {
    def funPartional:PartialFunction[String,Int]={//代表进来String类型,出去Int类型
      case "hello"=>1
      case "world"=>2
      case _=>0
    }
//    println(funPartional("gree"))
     val worlds=List("hello","world","gree","kb09")
     worlds.collect(funPartional).foreach(println)
//     worlds collect funPartional foreach println //省略.和(),效果和上方一样
    for (elem <- worlds.collect(funPartional)) {println(elem)}  //for循环强制遍历效果和foreach一样。

    //练习1
    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)
   // for (elem <- sex.collect(par1)) {println(elem)}

    //练习2
    def funTupple:PartialFunction[Char,(Char,Int)]={//输入Char,输出二元组。
      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)})

    //练习3
    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)
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值