我是 Scala 的新手,我正在尝试解码它的结构,我了解了模式匹配,语法类似于 Java switch 语句
val x: Int = Random.nextInt(10)
x match {
case 0 => "zero"
case 1 => "one"
case 2 => "two"
case _ => "other"
}
这里的代码非常明显且可读。我遇到了部分功能,它们非常明显并且很清楚它们是什么
偏函数是一个函数,它不能为它可以给出的每个可能的输入值提供答案。
我感到困惑的是case
在这样的部分函数的主体中使用:
val divide2: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 42 / d // WHAT IS THIS ?!
}
我不明白如何case
在没有match
语句的情况下使用,Scala 如何解释它,它是如何读取的,它是一个方法、一个类还是另一个构造?,我可以case
在没有match
语句的情况下使用哪些其他方式
编辑:
我试图玩弄这个案例,但仍然没有得到它。例如
val SomeFun: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 1000 / d
case f: Int if f != 2 => 100 / f
case m: Int if m != 1 => 10 / m
}
这是如何运作的?
尝试这样做会出错
val SomeFun = {
case d: Int if d != 0 => 1000 / d
case f: Int if f != 2 => 100 / f
case m: Int if m != 1 => 10 / m
}
Error:(29, 17) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: ?
不匹配的大小写是否在偏函数之外的其他任何地方使用?