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
[HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
Moderator: admin
-
- Posts: 167
- Joined: Sun Apr 21, 2024 10:43 am
- Contact:
-
- Posts: 1
- Joined: Thu Sep 26, 2024 4:45 am
- Contact:
Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
Sorry, but I still don't really understand this code. How does the return statement work?raphaelzintec wrote: ↑Tue Sep 24, 2024 1:38 pmvoid 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
-
- Site Admin
- Posts: 10386
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: [HD-OCP17/21-Fundamentals Pg 242, Sec. 10.2.1 - using-instanceof-as-a-pattern-matching-operator]
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.
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.
Who is online
Users browsing this forum: Bing [Bot] and 7 guests