Вот упрощенный фрагмент кода:
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)
Результат:
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
Здесь метод cal c вызывается дважды для результат 1, 2, 3. Предположим, что метод cal c является дорогостоящим, тогда как избежать дублирования его вызовов при каждом вызове частичной функции pf ?