Adam Warski
Feb 5, 2021

--

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.

--

--

Adam Warski

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