In the second case (if (myValue instanceof String && myValue.length() > 42)), you can’t call .length() on myValue, as for the compiler that value has another type (e.g. Object). So this would not compile. This is unlike in TypeScript, for example, where you have flow typing.

Hence, you need to (a) check that the value is of the given class, (b) cast that value to a new variable with the correct type and (c) call the method. The above syntax allows you to shorten (a) and (b) into one expression.

Software engineer, Functional Programming and Scala enthusiast, SoftwareMill co-founder

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store