Page 1 of 1
[HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
Posted: Tue Sep 24, 2024 1:38 pm
by raphaelzintec
void main(String[] args){
Object obj = getObject(args.length);
if(! (obj instanceof String str) ){
//will not compile if return statement is commented out
return; //or a throw an exception!
}
System.out.println("str = "+str);
}
this out of scope has no real logic, it works only with ! operator and empty return.
Why i mean by that is that compiler doesnt care if its true or false, it will be correct
Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
Posted: Thu Sep 26, 2024 4:47 am
by pheroidsmok
raphaelzintec wrote: ↑Tue Sep 24, 2024 1:38 pm
void main(String[] args){
Object obj = getObject(args.length)
geometry dash;
if(! (obj instanceof String str) ){
//will not compile if return statement is commented out
return; //or a throw an exception!
}
System.out.println("str = "+str);
}
this out of scope has no real logic, it works only with ! operator and empty return.
Why i mean by that is that compiler doesnt care if its true or false, it will be correct
Sorry, but I still don't really understand this code. How does the return statement work?
Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
Posted: Thu Sep 26, 2024 8:34 pm
by admin
The return statement ensures that there is no path left in the code that the control can take when obj is not an instance of String. Therefore, the compiler knows for sure that str will be in scope everywhere else. This is why str is available outside the if block.
Without the return statement, the print statement will be executed even when !(obj instanceof String str) is false. But in that case str will not be in flow scope and so the compiler refuses to accept this code.