Skip to content

Fix foldLeft and foldRight return types - #77

Closed
axlon wants to merge 1 commit into
schmittjoh:masterfrom
axlon:fold-return-type
Closed

Fix foldLeft and foldRight return types#77
axlon wants to merge 1 commit into
schmittjoh:masterfrom
axlon:fold-return-type

Conversation

@axlon

@axlon axlon commented Aug 14, 2024

Copy link
Copy Markdown
Contributor

The following code is valid, but not allowed by template types currently. This PR fixes that.

$some = new Some(5);
$result = $some->foldLeft(1, function($a, $b) { return (string) ($a + $b) }); // string("6")

@ojhaujjwal

Copy link
Copy Markdown

@GrahamCampbell Can we get this merged please if all okay?

plus my PR too #78 around the same issue.

@GrahamCampbell

Copy link
Copy Markdown
Collaborator

Thanks for spotting this, and you're right that the current annotation is too strict. As written though, @return R overshoots in the other direction: None::foldLeft() returns the initial value at runtime, so the true return type is S|R, and PHPStan flags None itself under this change. I've put up #82 which types the base methods as S|R with exact overrides on Some and None, so closing this in favour of that.

@GrahamCampbell

Copy link
Copy Markdown
Collaborator

The current @return S on the folds is indeed too strict, but changing it to @return R isn't right either: Some returns the callback result, while None just hands back the initial value, so the honest return type is the union of the two. Annotating R alone would have PHPStan bless code that blows up on the None path, and it fails the library's own analysis run. I've fixed this in #82 by returning S|R on the base class with exact overrides on Some and None. Thanks for spotting the problem and the nudge in the right direction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants