scala 偏函数
Posted jason-dong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scala 偏函数相关的知识,希望对你有一定的参考价值。
package com.jason.qianfeng object PartialFuncTest { def div: PartialFunction[Int, Int] = { case i if i != 0 => 100 / i } def r1: PartialFunction[Int, String] = { case 1 => "one" case 2 => "two" case _ => "other" } def r2: PartialFunction[Int, String] = { case 1 => "one" } def r3: PartialFunction[Int, String] = { case 2 => "two" } def r4: PartialFunction[Int, String] = { case _ => "other" } def r6: PartialFunction[String, String] = { case "one" => "haha one" case "two" => "wawo two" } def main(args: Array[String]): Unit = { val s = "=" * 10 println(s"$s test function div $s") println(s"div.isDefinedAt(0):" + div.isDefinedAt(0)) println(s"div.isDefinedAt(1):" + div.isDefinedAt(1)) println(s"div(2) = " + div(2)) println(s"$s test function r1 $s") println(s"r1(2) = " + r1(2)) println(s"$s orElse $s") val r5 = r2 orElse r3 orElse r4 println(s"r5(2) = " + r5(2)) println(s"$s andThen $s") val r7: PartialFunction[Int, String] = r1 andThen r6 println(s"r7(1) = " + r7(1)) } }
执行结果
========== test function div ========== div.isDefinedAt(0):false div.isDefinedAt(1):true div(2) = 50 ========== test function r1 ========== r1(2) = two ========== orElse ========== r5(2) = two ========== andThen ========== r7(1) = haha one
总结
1.什么是偏函数:例如上述的函数div,传入的参数为 int,反汉之也是int,但是函数并不是对所有输入的int都进行处理,而是只处理不为0 的int
2.orElse 方法可以拼接多个偏函数,类似if...else
3.andThen 方法是把多个偏函数串联起来,第一个函数的结果作为参数传给第二个,以此类推
以上是关于scala 偏函数的主要内容,如果未能解决你的问题,请参考以下文章