The takeIf fallacy

Response is a sealed class. A response can be either Success or Error and nothing else. A Success encapsulatesData. An Error encapsulates Exception.

The function getAnswer takes response as a parameter and if this response is Success returns the data-id else the exception message.

Let’s test it.

throws java.lang.ClassCastException

And BOOM java.lang.ClassCastException because Error cannot be cast to Success. Every time thegetAnswer is called the cast(response as Response.Success).data.id is executed.

takeIf function is not an if.

Kotlin documentation on how to use takeIf and takeUnless functions.

Enjoy Responsibly

References:

  1. https://kotlinlang.org/docs/reference/sealed-classes.html#sealed-classes
  2. https://kotlinlang.org/docs/reference/scope-functions.html#takeif-and-takeunless

--

--

Kyriakos Georgiopoulos

Android Software Engineer @vodafone.gr, fitness, bodybuilding and powerlifting enthusiast https://www.linkedin.com/in/kyriakos-georgiopoulos/