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
Adam Warski

Adam Warski

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

More from Medium

Enable Smile serialization on requests using Spring WebClient (Kotlin)

Functors with Scala & Cats 🐱​

Writing Robust Hoon — A Guide To Urbit Unit Testing

We release all apps together when the common lib is released. Don’t do it like us.