DEV Community

Discussion on: From Java 8 to Java 15 in Ten Minutes

Collapse
 
martinhaeusler profile image
Martin Häusler

"Instanceof without the cast" unfortunately doesn't work the way you describe in your example. You still need to assign a new variable name to the casted instance:

Object obj = new String("hello");
if (obj instanceof String mystr) {
  System.out.println("String length: " + mystr.length());
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pmgysel profile image
Philipp Gysel

Thanks Martin, there's always a bug somewhere! I updated the code snippet as you suggested 😎

Collapse
 
martinhaeusler profile image
Martin Häusler

No problem. I really wish they did it in the way you've described. If you want this kind of inference, you'd have to use Kotlin; there it works this way.

Thread Thread
 
pmgysel profile image
Philipp Gysel

Oh well I‘m jeleous of the Kotlin developers😜 Anyways, happy coding!