The takeIf fallacy

Photo by Deva Darshan on Unsplash

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

--

--

--

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

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

Recommended from Medium

Crodo Competitor Review — AvaxLauncher

Abstraction in Software Engineering

Rest API Testing using JMeter | API Testing Tutorial | Day 28

The Blind 75 Leetcode Series: Rotate Image

Print X array elements closest to the Kth smallest element in the array

Developing a Wireless Sensor Network (WSN) and Internet of Things (IoT) system over the AWS Cloud

Spark + Data Compaction

3 Habits Of Highly Effective Engineers

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
Kyriakos Georgiopoulos

Kyriakos Georgiopoulos

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

More from Medium

Jetpack Compose for Views developers — LinearLayout

Support for Split Application Binary (.OBB)

Creating a Custom Button Using PorterDuff.Mode

RecycleView Kotlin — Android Studio