对给定的输入参数类型,函数可接受该类型的任何值。换句话说,一个(Int) => String 的函数可以接收任意Int值,并返回一个字符串。

    对给定的输入参数类型,偏函数只能接受该类型的某些特定的值。一个定义为(Int) => String 的偏函数可能不能接受所有Int值为输入。
    **isDefinedAt 是PartialFunction的一个方法,用来确定PartialFunction是否能接受一个给定的参数。

    1. scala> val one: PartialFunction[Int, String] = { case 1 => "one" }
    2. one: PartialFunction[Int,String] = <function1>
    3. scala> one.isDefinedAt(1)
    4. res0: Boolean = true
    5. scala> one.isDefinedAt(2)
    6. res1: Boolean = false
    7. scala> one(1)
    8. res2: String = one

    PartialFunctions可以使用orElse组成新的函数,得到的PartialFunction反映了是否对给定参数进行了定义。

    1. scala> val two: PartialFunction[Int, String] = { case 2 => "two" }
    2. two: PartialFunction[Int,String] = <function1>
    3. scala> val three: PartialFunction[Int, String] = { case 3 => "three" }
    4. three: PartialFunction[Int,String] = <function1>
    5. scala> val wildcard: PartialFunction[Int, String] = { case _ => "something else" }
    6. wildcard: PartialFunction[Int,String] = <function1>
    7. scala> val partial = one orElse two orElse three orElse wildcard
    8. partial: PartialFunction[Int,String] = <function1>
    9. scala> partial(5)
    10. res24: String = something else
    11. scala> partial(3)
    12. res25: String = three
    13. scala> partial(2)
    14. res26: String = two
    15. scala> partial(1)
    16. res27: String = one
    17. scala> partial(0)
    18. res28: String = something else

    case 的一个使用场景

    1. scala> case class PhoneExt(name: String, ext: Int)
    2. defined class PhoneExt
    3. scala> val extensions = List(PhoneExt("steve", 100), PhoneExt("robey", 200))
    4. extensions: List[PhoneExt] = List(PhoneExt(steve,100), PhoneExt(robey,200))
    5. scala> extensions.filter { case PhoneExt(name, extension) => extension < 200 }
    6. res0: List[PhoneExt] = List(PhoneExt(steve,100))

    为什么这段代码可以工作?

    filter使用一个函数。这个函数应该是 (PhoneExt) => Boolean。

    PartialFunction是Function的子类型,所以filter也可以使用PartialFunction!