Scala学习——Lambda表达式、部分函数、偏函数

Lambda表达式、部分函数、偏函数

Lambda表达式


public interface stu  {
    public  Integer opstu(Integer a,String b);

}

public class opstulmpl implements stu {
    @Override
    public Integer opstu(Integer a, String b) {
        return a;
    }
}
						
public class TestDemo {
    public static void main(String[] args) {
        stu salary=(Integer a,String content) ->{
            if(content.equals("初中")&a==18){
                return 2000;
            }else if(content.equals("高中")&a==20){
                return 2200;
            }else if(content.equals("大专")&a==21){
                return 2400;
            }else if(content.equals("本科")&a==24){
                return 3000;
            }else{
                return 0;
            }
        };
        System.out.println(salary.opstu(18,"初中"));

部分函数

//部分函数
   def showMsg(title:String,content:String,num:Int)={
     println(title+":"+content+" "+num)
   }
  //showMsg("警告","当前水位是",12)

  val title="警告"
  def showWaterAlter=showMsg(title,_:String,_:Int)

  //showWaterAlter("当前水位",14)

  def add(a:Int,b:Int,c:Int):Unit={
    println(a + b + c)
  }
  val aa=10
  def add1=add(aa,_:Int,_:Int)

  //add1(45,25)

偏函数

 //偏函数
  def funPartitional:PartialFunction[String,Int]={
    case "hello"=>1
    case "World"=>2
    case _ =>0
  }
//  val num=funPartitional("djflsf")
//  println(num)

//  val worlds=List("hello","world","gree","kb09")
//  val ints: List[Int] = worlds.collect(funPartitional)
//  worlds collect funPartitional foreach println

//  def diao:PartialFunction[String,Int]={
//    case "hehe"=>2
//    case "niu"=>1
//    case _ => 0
//  }
//  println(diao("hehe"))
//  println(diao("niu"))
//  println(diao("djfdsf"))
//
//  def funGender:PartialFunction[String,Int]={
//    case "male"=>1
//    case "female"=>0
//    case "男"=>1
//    case "女"=>0
//    case _ => -1
//  }
//  println(funGender("男"))
//  println(funGender("女"))
//  println(funGender("fsdffs"))

  def funTupple:PartialFunction[Char,(Char,Int)]={
    case 'A'=>('A',1)
    case 'B'=>('B',1)
    case _=>('X',1)
  }
//  val tuple:(Char,Int)=funTupple('A')
//  print(tuple)
  val chars=List('A','B','C','D')
  val tuples:List[(Char,Int)]=chars.collect(funTupple)
  //tuples.foreach(tp=>println(tp._1))

  def fun2:PartialFunction[Any,Int]={
    case i:Int=>i
    case _=> 0
  }
  var list=List("a","c",2,2.5,3,4,6)
  list.collect(fun2).foreach(println)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值