Skip to content

Correct behavior of flatMap method - #52

Open
petrknap wants to merge 1 commit into
mainfrom
fixed-flatmap
Open

petrknap wants to merge 1 commit into
mainfrom
fixed-flatmap

Conversation

@petrknap

@petrknap petrknap commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner
  • This pull request does not contain any breaking change.
  • I asked the AI to briefly summarize, use and improve the feature(s), and I'm okay with the output:

What do you think about this change?

Based on the provided diff and code files, this change refactors the flatMap method and its signature across the Optional library to align more closely with standard Java SE 8 Optional semantics.

Here is a breakdown of what the changes accomplish:

1. flatMap Return Type and Behavior Shift

  • Java SE 8 Alignment: Previously, flatMap included custom handling for empty states and strict type coercion/validation on return values. The updated implementation simplifies flatMap to return JavaSe8\Optional directly (V|self<U> in Optional and V|JavaSe8\Optional<U> in the interface).

  • Short-circuiting Empty States: When an Optional is empty ($this->value === null), flatMap now immediately returns $this (or an empty optional instance) rather than passing through a custom empty argument.

2. Cleaner Code and Removed Overengineering

  • Removal of the $empty parameter: The optional $empty parameter and the internal match block checking various return types inside Optional::flatMap have been removed. The function now directly executes and returns the result of the $mapper callback when a value is present.

  • Trait and Interface Consistency: OptionalOverrides and JavaSe8\Optional have been updated to match these revised method signatures and generic type templates (@template V of JavaSe8\Optional<U>).

3. Test Suite Updates

  • Refined PHPDoc and Tests: The phpdoc_check.php and test files (OptionalTest.java and AnotherOption.php) were updated to reflect the new return types, ensuring static analysis tools like PHPStan correctly validate the contract without needing extra workarounds.

Overall, this is a clean refactoring step that reduces complexity, removes redundant code, and makes the library's flatMap implementation leaner and more faithful to standard expectations.

@petrknap petrknap self-assigned this Oct 13, 2026
@petrknap petrknap added the bug Something isn't working label Oct 13, 2026
@petrknap
petrknap marked this pull request as ready for review October 14, 2026 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant