Skip to content

Instantly share code, notes, and snippets.

@meowpunch
Last active January 12, 2022 07:24
Show Gist options
  • Save meowpunch/a6a1ab0dba98ccd5b372fc837c8c1b2d to your computer and use it in GitHub Desktop.
Save meowpunch/a6a1ab0dba98ccd5b372fc837c8c1b2d to your computer and use it in GitHub Desktop.
Type patterns, `instanceof` operator, Java
// 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