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.
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: