//学习偏函数 object PartialFunctionDemo { //定义一个普通的函数 val div1 = (x: Int) => 100 / x val div2 = new PartialFunction[Int, Int] { override def isDefinedAt(x: Int): Boolean = x != 0 override def apply(v1: Int): Int = 100 / v1 } //使用case定义偏函数 val div3: PartialFunction[Int, Int] = { case d: Int if (d != 0) => 100 / d } val div4: PartialFunction[Int, String] = { case 1 => "one" case 2 => "two" case _ => "other" } def main(args: Array[String]): Unit = { // div1(0) println(div2.isDefinedAt(1)) println(div2.isDefinedAt(0)) println(div1(1)) // println(div1(0)) println(div3(1)) println(div4.isDefinedAt(1)) println(div4.isDefinedAt(3)) println(div4(0)) //orElse组合多个偏函数,变成一个整体 val r1: PartialFunction[Int, String] = { case 1 => "one" } val r2: PartialFunction[Int, String] = { case 2 => "two" } val r3: PartialFunction[Int, String] = { case _ => "other" } //res2等价于div4 val res2 = r1.orElse(r2).orElse(r3) println(res2(0)) //andThen 连接函数 val r4: PartialFunction[Int, String] = { case c: Int if (c == 1) => "one" } val r5: PartialFunction[String, String] = { case c: String if (c eq "one") => "success" } val r6 = r4.andThen(r5) println(r6(1)) } } |
scala自学之路-31-偏函数
最新推荐文章于 2024-11-07 11:39:01 发布
本文探讨了Scala中的偏函数(PartialFunction)及其应用。通过实例展示了如何定义、使用和组合偏函数,包括使用case定义偏函数、orElse组合多个偏函数以及andThen连接函数,揭示了Scala函数式编程的灵活性和强大功能。
摘要由CSDN通过智能技术生成