Scala快速入门-函数组合

compose&andThen

两个函数组装为一个函数,compose和andThen相反

    def f(test: String):String = {
      "f(" + test + ")"
    }
    def g(test: String):String = {
      "g(" + test + ")"
    }
    val composeFunction = f _ compose g _
    println("compose result:%s".format(composeFunction("compose")))
    val andThenResult= f _ andThen g _
    println("andThen result:%s".format(andThenResult("compose")))

执行结果

compose result:f(g(compose))
andThen result:g(f(compose))

PartialFunction

对给定的输入参数类型,偏函数只能接受该类型的某些特定的值。一个定义为(Int) => String 的偏函数可能不能接受所有Int值为输入。
isDefinedAt 是PartialFunction的一个方法,用来确定PartialFunction是否能接受一个给定的参数。

    val one: PartialFunction[Int, String] = { case 1 => "one" }
    println(one.isDefinedAt(1))
    println(one.isDefinedAt(2))
    val two: PartialFunction[Int, String] = { case 2 => "two" }
    val three: PartialFunction[Int, String] = { case 3 => "three" }
    val wildcard: PartialFunction[Int, String] = { case _ => "something else" }
    //PartialFunctions可以使用orElse组成新的函数,
    //得到的PartialFunction反映了是否对给定参数进行了定义。
    val partial = one orElse two orElse three orElse wildcard
    println(partial(1))
    println(partial(4))

执行结果:

true
false
one
something else

广告

点击Spark加入群Spark,分享更多Spark相关信息

转载于:https://www.cnblogs.com/jacksu-tencent/p/4216389.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值