Re: [RFC] Return Type Declarations

From: Date: Tue, 29 Apr 2014 01:19:57 +0000
Subject: Re: [RFC] Return Type Declarations
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-73837@lists.php.net to get a copy of this message
On Mon, Apr 28, 2014 at 3:43 PM, Larry Garfield <larry@garfieldtech.com>wrote: > On 4/28/14, 3:30 PM, Levi Morrison wrote: > > As I write that I suspect it's because generators actually "return" an >>> interator object, and so the return type of the generator is being >>> interpreted relative to the construction, not iteration, of the >>> generator. >>> That seems like a likely source of confusion, as I would, as a >>> developer, >>> expect to be specifying the type that gets returned from iteration, not >>> from construction, so that my foreach loop (or similar) can rely on the >>> type being returned. >>> >>> >> The type hint is purposefully not the type of the value returned; a >> generator always returns a generator. I will clarify this in the RFC and >> maybe adjust the wording in the error message as well to better indicate >> this. >> > > So I suppose technically we should say that a generator must always return > a Traversable? Not quite: a generator always returns a Generator (this is an actual object); so it can fulfill Generator, Iterator and Traversable. > > I think this part warrants further consideration. The rest of the RFC I >>> fully look forward to using. >>> >> >> Special casing a generator's return type would be an inconsistency in the >> design. If you var_dump() something that returns generator it tells you it >> is a generator; this should match the type of the return value and >> anything >> else is unexpected. As an example, using a generator to fulfill an >> Iterator >> return type should succeed; special casing the Generator would complicate >> the code to achieve this. Special casing the generator would also infringe >> on other future ideas, such as adding generics to the language. All in >> all, >> special casing generators doesn't make sense. >> > > That makes sense from an engine point of view, certainly. From a user > POV, I can still see it being the source of much confusion. I confess I've > barely used generators so far (PHP 5.5 still having very small market > penetration), but it feels natural to mentally align return type / return > keyword and return type / yield keyword. It also means I have no way of > declaring that a generator will always return items of type X, which seems > like a valid thing to do. Agreed; however I would rather have all kinds of Iterators and collection like object be able to type their values too. This would obviously fall outside of this RFC so I have specifically left this possibility open without directing its future too much.

« previous php.internals (#73837) next »