4 ms·
These Java features are ruined by not allowing mutable variables to be captured. Having to do the 1-element array trick when the compiler could just do it for m
by ErikCorry 2y ago
These Java features are ruined by not allowing mutable variables to be captured. Having to do the 1-element array trick when the compiler could just do it for me is insane.
If you are making JavaScript look good you are failing as a language.
- cess11 2y agoTypically I can use a forEach in such cases, and when I can't it's probably an incrementer and the IDE just switches out my int as an automatic solution to its complaint. I think its OK to be reminded that the context is mainly immutable when chaining on a stream. Method polymorphism to achieve default parameter values is a much worse nuisance, but not particularly hard to get used to when one decides to focus on the problem rather than the inevitable warts of a broadly useful programming language. Edit: Also a pretty weird complaint in a thread about a programming language where pretty much all the basic data structures are immutable. Maybe take it to the top and make the quip about worse than JavaScript with regards to Clojure?
- ErikCorry 2y agoDoesn't the forEach method on arrayList have the exact same issue?
- kaba0 2y agoYou mean not having the error that go just fixed by changing the language is a problem?
- ErikCorry 2y agoJS has this error too, but nothing forces Java to have this issue if they fix the no-mutable-captures problem. Dart got this right from the start. Here's JS showing the same issue. for (var i = 0; i < 10; i++) { array.push(() => i) } array.forEach((fn) => console.log(fn())) // Prints 10 every time. The correct fix is that each loop iteration gets a fresh i instead of i just being mutated. Currently you can't see the difference in Java between there-is-only-one-i and there-is-a-fresh-i-every-time, so Java is free to do this right.
- cess11 2y agoHere's what I'd do: array = []; function clos(val) { return () => val; } for (var i = 0; i < 10; i++) { array.push(clos(i)); } array.forEach(fn => console.log(fn())); This outputs 0-9 instead of 10, though I'm just a silly self-taught person that never got schooled at these things, maybe there is some reason not to use closures that I don't know about.
- ifwinterco 2y agoThese days in JS you can just use let instead of var and it will work, but in itself that inconsistency is a bit weird
- cess11 2y agoYeah, let/const is what I tend to use. Here I wanted to change someone else's code as little as possible. Edit: Oh, right, it also solves the 10-issue. Thanks, didn't realise at first.