【Scala】09 偏函数 PartialFunction

 

更像是策略函数

可拆分成一个部分,是若干个函数的组合

package cn

object HelloScala {
  def main(args: Array[String]): Unit = {
    // 偏函数 对输入参数进行强化检查


    // 案例需求
    val list : List[(String, Int)] = List(("a", 12), ("b", 35), ("c", 44), ("d", 55))

    // map转换 key不变, value2倍
    val newList = list.map(tuple => (tuple._1, tuple._2 * 2))

    // 模式匹配对元组元素赋值实现功能
    val newList2 = list.map(tuple => {
      tuple match  {
        case (a, b) => (a, b * 2)
      }
    })

    // 省略Lambda表达式写法 偏函数
    val newList3 = list.map{
      case (a, b) => (a, b * 2)
    }

    println(newList)
    println(newList2)
    println(newList3)

    // 偏函数
    val positiveAbs : PartialFunction[Int, Int] = {
      case a if a > 0 => a
    }
    val negativeAbs : PartialFunction[Int, Int] = {
      case a if a < 0 => -a
    }
    val zeroAbs : PartialFunction[Int, Int] = {
      case 0 => 0
    }

    // 声明
    def abs(x : Int) : Int = (positiveAbs orElse negativeAbs orElse zeroAbs)(x)

  }
}

 

上一篇:21.元组内置


下一篇:Python作业4