zoukankan      html  css  js  c++  java
  • Scala Partial Function从官方文档解析

    A partial function of type PartialFunction[A, B] is a unary function where the domain does not necessarily include all values of type A.

    一个PartialFunction[A, B]类型的偏函数是一个一元函数。它的输入值的范围并不包含所有A类型的值。

    The function isDefinedAtallows to test dynamically if a value is in the domain of the function.

    给定一个A类型的值,isDefinedAt函数可以用来动态地检测这个值是否属于此偏函数的输入范围。

    Even if isDefinedAt returns true for an a: A, calling apply(a) may still throw an exception, so the following code is legal:

    val f: PartialFunction[Int, Any] = { case _ => 1/0 }

    如果有一个a: A,虽然isDefinedAt返回true,但apply(A)可能会返回一个异常。

    It is the responsibility of the caller to call isDefinedAt before calling apply, because if isDefinedAt is false, it is not guaranteed apply will throw an exception to indicate an error condition. If an exception is not thrown, evaluation may result in an arbitrary value.

    调用者有责任在调用apply之前先调用isDefinedAt来做检查。因为如果isDefinedAt返回了false,apply方法并不能保证能做出抛异常的回应,有可能返回了意料之外的值。

    The main distinction between PartialFunction and scala.Function1 is that the user of a PartialFunction may choose to do something different with input that is declared to be outside its domain. For example:

    偏函数和Function1的区别是,偏函数的用户可以选择对输入域以外的输入值做一些特殊的处理。

    val sample = 1 to 10
    val isEven: PartialFunction[Int, String] = {
      case x if x % 2 == 0 => x+" is even"
    }
    
    // the method collect can use isDefinedAt to select which members to collect
    val evenNumbers = sample collect isEven
    
    val isOdd: PartialFunction[Int, String] = {
      case x if x % 2 == 1 => x+" is odd"
    }
    
    // the method orElse allows chaining another partial function to handle
    // input outside the declared domain
    val numbers = sample map (isEven orElse isOdd)
  • 相关阅读:
    tcpdump 抓包
    mysql常用日期函数
    接口自动化测试,一键快速校验接口返回值全部字段
    实训项目
    vue proxyTable 代理方式 解决 跨域pathRewrite
    cookie, session, token 发展史
    Failed to set locale, defaulting to C.UTF-8
    java String与Integer的相互转化
    java LocalDateTime 常用 转换 方法
    Java命令里面的EQ、NE、GT、LT、GE、LE分别代表含义
  • 原文地址:https://www.cnblogs.com/shuada/p/5039133.html
Copyright © 2011-2022 走看看