Here is a simplified code snippet:
val pf = new PartialFunction[Int, Int]
{
private def calc(x: Int): Int = x - 3
override def isDefinedAt(x: Int): Boolean =
{
val result = calc(x)
println(s"calc is called by isDefinedAt, result = $result")
result > 0
}
override def apply(x: Int): Int =
{
val result = calc(x)
println(s"calc is called by apply, result = $result")
result
}
}
(0 to 6).collect(pf)
The output is:
calc is called by isDefinedAt, result = -3
calc is called by isDefinedAt, result = -2
calc is called by isDefinedAt, result = -1
calc is called by isDefinedAt, result = 0
calc is called by isDefinedAt, result = 1
calc is called by apply, result = 1
calc is called by isDefinedAt, result = 2
calc is called by apply, result = 2
calc is called by isDefinedAt, result = 3
calc is called by apply, result = 3
Here, the calc method is called twice for result 1, 2, 3. Suppose that the the calc method is costly, then how to avoid duplicate calls to it for each call to the partial function pf?