Sometimes, people just get carried away with new features



  • var ar = Enumerable.Range(1, 12);
    foreach (var i in ar)
    {
       //...
    }
    

  • BINNED

    Where's the switch? I mean, this is PERFECT. Foreach switch on an enumerable!



  • What feature are you referring to? foreach on Enumerable.Range instead of a plain old for loop?

    I've used this pattern plenty of times, but only when the Enumerable.Range was followed by Select or some such nonsense...



  • This is exactly how you do loops in python though. There is only for-each.



  • If you want to see awkward, this is the Java 8 version of the same thing:

    import java.util.stream.IntStream;
    
    IntStream ar = IntStream.range(1, 12);
    for (Integer i in ar)
    {
        //...
    }
    

    ...or at least it is as far as I can tell from the documentation.

    Well, that's not as awkward as I thought once I realized it returns Integer instead of OptionalInt

    Edit: Still, for a stream specifically built for returning primitives, why does next return an object? Because people are too lazy to call hasNext? But then there's nextInt which does return a primitive...



  • Does it implement the weakly typed Iterator interface?

    Edit: Wow, OptionalInt sounds like all the drawbacks of .Net's System.Nullable<int> without its advantages (like being a value type, which by definition can't throw a NullReferenceException at you when checking its HasValue property)...



  • @Medinoc said:

    Does it implement the weakly typed Iterator interface?

    I'd have to go up the Iterator's inheritance chain.

    It's an instance of the PrimitiveIterator.OfInt interface, which extends PrimitiveIterator<Integer,IntConsumer>, which extends Iterator<T> (in this case, Iterator<Integer>)

    So.... yes.

    @Medinoc said:

    Edit: Wow, OptionalInt sounds like all the drawbacks of .Net's System.Nullable<int> without its advantages (like being a value type, which by definition can't throw a NullReferenceException at you when checking its HasValue property)...

    That's exactly what I was thinking.



  • Except it's a "value-based" type, which means that at some point in the future, they're going to optimize it into a plain int - except when it's null, which will trigger deoptimization. Fun fun fun!


  • Discourse touched me in a no-no place

    @powerlord said:

    Still, for a stream specifically built for returning primitives, why does next return an object?

    Because the stream is implementing the Iterable interface (that's what the next() method is part of, and what the foreach relies on) and the Java generic type logic works over reference types only.


Log in to reply