Skip to content

Commit e80a9f4

Browse files
[data] optimize Maybe.collect (#1083)
<!-- PRs require an approval from any of the core contributors, other than the PR author. Include this header if applicable: Fixes #issue1, #issue2, ... --> ### Problem The current implementation of `Maybe.collect` checks if the partial function is defined on the input value before calling it. This can be sub-optimal, as it causes a double evaluation of pattern matchers and guards in the partial function (once on the call to `pf.isDefinedAt(value)` and once on the application `pf(value)`. ### Solution <!-- Describe your solution. Focus on helping reviewers understand your technical approach and implementation decisions. --> Using the `applyOrElse` method allows optimized implementations of `PartialFuncion`, such as partial function literals (mentioned in https://github.com/scala/scala/blob/780d80c714354871bc5972045926b7ccd042e102/src/library/scala/PartialFunction.scala#L194) to avoid double evaluations of guards. --------- Co-authored-by: Flavio Brasil <[email protected]>
1 parent b083b22 commit e80a9f4

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

kyo-data/shared/src/main/scala/kyo/Maybe.scala

+4-8
Original file line numberDiff line numberDiff line change
@@ -324,14 +324,8 @@ object Maybe:
324324
* a new Maybe containing the result of the partial function if defined and applicable, or Absent otherwise
325325
*/
326326
inline def collect[B](pf: PartialFunction[A, B]): Maybe[B] =
327-
if !isEmpty then
328-
val value = get
329-
if pf.isDefinedAt(value) then
330-
pf(value)
331-
else
332-
Absent
333-
end if
334-
else Absent
327+
if isEmpty then Absent
328+
else pf.applyOrElse(get, constAbsent)
335329

336330
/** Returns this Maybe if defined, or an alternative Maybe if empty.
337331
*
@@ -445,5 +439,7 @@ object Maybe:
445439
else
446440
new PresentAbsent(depth)
447441
end PresentAbsent
442+
443+
val constAbsent: Any => Absent = _ => Absent
448444
end internal
449445
end Maybe

0 commit comments

Comments
 (0)