3 ms·
It's always bothered me how public A(String s) { this(s.isEmpty()); } is allowed but public A(String s) { boolean helpfulName = s.isEmpty();
by charcircuit 4y ago
It's always bothered me how
public A(String s) {
this(s.isEmpty());
}
is allowed but
public A(String s) {
boolean helpfulName = s.isEmpty();
this(helpfulName);
}
isn't
- layer8 4y agoYes, though in that case you can use public A(String s) { this(helpfulName(s)); } with a static method.
- kaidon 4y agobingo - exactly the way to do it in java
- dehrmann 4y agoThere's something to be said for making sure the parent constructor is the first call made. It means any method you call in the current constructor will work correctly or obviously be your fault, not the parent class's. Yes, in your particular case, the compiler could figure out that you're not using "this," but you can only make a compiler so clever.
- cdcarter 4y agoIt's not too hard to make the compiler (or more specifically, the language) know about this. The solution isn't even that clever, you just don't put "this" into scope until the super() call.
- klntsky 4y agoIt's not that simple, because you can't find where super is called in the general case. Consider: `var foo = { bar: super }; foo['b' + 'a' + 'r']();` - you need to evaluate it in order to define scoping. But JS has lexical scoping as a design choice...
- adrianmsmith 4y agoThis article is about Java, your comment is about JavaScript.
- klntsky 4y agoOoof. Didn't realize it. Still, I believe the same applies, we can't dynamically analyze pointers at the time scoping must be settled.
- int_19h 4y agoWhat does it have to do with pointers? super() in Java is a special language construct, it's not a method that you can have a pointer to. Thus it can be analyzed exactly the same as e.g. definitive variable assignment, and "this" be unavailable on any codepath on which super() has not been definitively called.