Sometimes, people just get carried away with new features
-
var ar = Enumerable.Range(1, 12); foreach (var i in ar) { //... }
-
Where's the switch? I mean, this is PERFECT. Foreach switch on an enumerable!
-
What feature are you referring to?
foreach
onEnumerable.Range
instead of a plain oldfor
loop?I've used this pattern plenty of times, but only when the
Enumerable.Range
was followed bySelect
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 ofOptionalInt
Edit: Still, for a stream specifically built for returning primitives, why does
next
return an object? Because people are too lazy to callhasNext
? But then there'snextInt
which does return a primitive...
-
Does it implement the weakly typed
Iterator
interface?Edit: Wow,
OptionalInt
sounds like all the drawbacks of .Net'sSystem.Nullable<int>
without its advantages (like being a value type, which by definition can't throw aNullReferenceException
at you when checking itsHasValue
property)...
-
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 extendsPrimitiveIterator<Integer,IntConsumer>
, which extendsIterator<T>
(in this case,Iterator<Integer>
)So.... yes.
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!
-
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 thenext()
method is part of, and what thefor
each relies on) and the Java generic type logic works over reference types only.