我是 Scala 的新手,我正在尝试 PartialFunctions,这是测试功能的正确方法吗,因为一些教程遵循此方法工作,但对我不起作用?
代码:
object MyScalaApp extends App {
def try29{
val r = new PartialFunction[Int, Int]
{
def isDefinedAt(q: Int) = q < 0 // Applying isDefinedAt method
def apply(q: Int) = 12 * q // Applying apply method
}
val rr = new PartialFunction[Double, Double]
{
def isDefinedAt(q: Double) = {q < 0}
def apply(q: Double) = 12 * q
}
println(r(1))
println(r(2))
println(rr(-1))
println(rr(-2))
}
}
try29
}
输出:
12
24
-12.0
-24.0
为什么 apply
在第一个条件不匹配时调用 get call?
当我写 def isDefinedAt(q: Int) = q != 0
它给出 println(r(0))
作为输出 0
最佳答案
根据ScalaDocs page :
It is the responsibility of the caller to call
isDefinedAt
before callingapply
...
让我们在自动调用 isDefinedAt()
的上下文中尝试您的 r()
部分函数。
val r = new PartialFunction[Int, Int] {
def isDefinedAt(q: Int) = q < 0
def apply(q: Int) = 12 * q
}
List(4,-3,22,-9,0).collect(r)
//res0: List[Int] = List(-36, -108)
似乎按预期工作。
关于带有 isDefinedA 的 Scala PartialFunction 并应用不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66058481/