I don't understand why we need IterableOnce ? Was: Proposal: JDK-8148917 Enhanced-For Statement Should Allow Streams

Peter Levart peter.levart at gmail.com
Mon Mar 18 09:37:06 UTC 2019

On 3/15/19 10:07 AM, Ivan Gerasimov wrote:
> On 3/15/19 1:51 AM, Peter Levart wrote:
>> On 3/15/19 9:38 AM, Ivan Gerasimov wrote:
>>> Hi Peter!
>>> On 3/15/19 1:24 AM, Peter Levart wrote:
>>>> On 3/15/19 9:03 AM, forax at univ-mlv.fr wrote:
>>>>>>       * @since 13
>>>>>>       */
>>>>>>      interface Once {}
>>>>>> What do you think of that?
>>>>> It's not clear to me if an annotation, available at runtime, is 
>>>>> not a better fit.
>>>>> Anyway, i'm not sure not sure introducing such 
>>>>> interface/annotation worth its maintenance cost, as you said the 
>>>>> use case is pretty narrow.
>>>> It is narrow, but in a situation like that, where you want to code 
>>>> an optimal generic algorithm and all you have access to is an 
>>>> Iterable, there's no other way (short of providing additional 
>>>> methods, which is ugly). Just think of this situation. You have to 
>>>> decide upfront if you need to buffer the elements obtained from 1st 
>>>> iteration or not, but 1st iteration always succeeds...
>>> Can you please explain how the interface Once would help to solve this?
>>> If an Iterable does not implement Once, it does not mean it allows 
>>> multiple passes, right?
>> It does not guarantee multiple passes, that's right, but that's 
>> legacy. This situation is the same for IterableOnce as a subtype of 
>> Iterable, but marker interface has less chance to intrude into 
>> "visible" static types that consist of method signatures, type 
>> parameters and variable types and therefore does not cause confusion 
>> in that area.
>> "Once" is not perfect, but allows generic algorithms to work on those 
>> instances that do implement it at least.
> Thanks for clarifying!
> My point was that in the situation you described, an interface Many 
> (or MultiPass, or how ever it's named) would be more appropriate.
> If an Iterable implements it, there is a guarantee.  Otherwise it has 
> to be assumed a one-shot Iterable.
> With kind regards,
> Ivan

Yes, that would be safer, but also less useful as most current 
implementations support multi-pass iteration and would have to be 
updated to implement this new interface. Unless majority of multi-pass 
capable implementations consist of Collection(s) in which case this 
"MultiPass" interface could be added as a super-interface to 

If this is true, then testing against java.util.Collection could be a 
usefull-enough runtime check for the edge cases of hypothetical generic 
algorithms that need multiple passes and we don't even need the 
"MultiPass" interface...

Regards, Peter

More information about the core-libs-dev mailing list