Skip to content
Advertisement

Utilizing switch statements with enums and marker interface

I’ve got a marker interface

JavaScript

and two enums which implement the Marker

JavaScript

What I’m trying to do is utilize a switch statement, such as

JavaScript

Is there a way to do this without using an expensive instanceof call?

Something like this would work, but I’m trying to avoid using instanceof, and frankly it looks kind of ugly.

JavaScript

Advertisement

Answer

Looks like a good scenario to try new Java Feature Sealed Interface and Pattern Matching for switch Expressions(* this is a preview feature as at jdk 17)

First make Marker as sealed interface

JavaScript

Then we can use switch expression to get rid of those instanceof checking.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement