zoukankan      html  css  js  c++  java
  • 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相关信息

  • 相关阅读:
    python学习day02
    鼓起勇气 大胆说不
    spring系列---- spring-mvc1
    win7-64位 jdk安装
    项目分层以及阶段期限规划
    老油条之记
    论软件与管理的关系---企业管理软件的末路
    软件项目管理之觞
    世界在变化-----谷歌不安全
    LPR利率与固定利率哪个更合算?
  • 原文地址:https://www.cnblogs.com/jacksu-tencent/p/4216389.html
Copyright © 2011-2022 走看看