Last active
January 12, 2022 07:24
-
-
Save meowpunch/a6a1ab0dba98ccd5b372fc837c8c1b2d to your computer and use it in GitHub Desktop.
Type patterns, `instanceof` operator, Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// without type patterns | |
if (obj instanceof String) { return ((String) s).length(); } | |
// type patterns, cast to String and assign to s | |
if (obj instanceof String s) { return s.length(); } | |
x instanceof String s && s.length() | |
// compile error, out of scope | |
x instanceof String s || s.length() | |
// refactor `area` method | |
... | |
public double area(Object shape) throws NoSuchShapeException { | |
if (shape instanceof Square s) return s.side * s.side; | |
else if (shape instanceof Rectangle r) return r.height * r.width; | |
else if (shape instanceof Circle c) return PI * c.radius * c.radius; | |
throw new NoSuchShapeException(); | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment