Benji's Blog

InstanceOf “Smart Casts” with Java 8 Lambdas

As with try-as-expression, there are many other language features we can simulate with Lambdas.

Another example is removing the cast commonly needed with instanceof. Kotlin has a nice feature called smart casts, which allows you to do

    if (x instanceof Duck) {
        x.quack();
    }

Where x is “casted” to Duck within the block.

I previously blogged how to simulate this in older Java using dynamic proxies.

Now in Java 8 you can do it in a slightly less terrible way, and also make it an expression at the same time.

    @Test
    public void should_return_value_when_input_object_is_instance() {
        Object foo = "ffoo";

        String result = when(foo).instanceOf(String.class)
                .then(s -> s.substring(1))
                .otherwise("incorrect");

        assertEquals("foo", result);
    }

More examples and implementation on github.