Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What can replace instanceof for java 11?

@Override
public int compareTo(@NotNull Object o) {
    if (o instanceof Task task) {
        if (task.getStartTime() == null) {
            return -1;
        } else if (task.getStartTime().isBefore(this.startTime)) {
            return 1;
        } else if (task.getStartTime().isAfter(this.startTime)) {
            return -1;
        } else return 0;
    } else throw new RuntimeException("Не наследник Task");
}
java: pattern matching in instanceof is not supported in -source 11
  (use -source 16 or higher to enable pattern matching in instanceof)

I can use only Java 11. How can I resolve this?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Change your code to this:

@Override
public int compareTo(@NotNull Object o) {
    if (o instanceof Task) {
        final Task task = (Task) o;
        if (task.getStartTime() == null) {
            return -1;
        } else if (task.getStartTime().isBefore(this.startTime)) {
            return 1;
        } else if (task.getStartTime().isAfter(this.startTime)) {
            return -1;
        } else return 0;
    } else throw new RuntimeException("Не наследник Task");
}

Prior to pattern matching you had to cast the class manually.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading