This article covers different ways to convert a Boolean to an Int in Kotlin. The conversion should be such that true is 1, and false is 0.

1. Conditional Statement

A fairly simple and common approach is to use a conditional statement (if-expression or when-expression) for conversion.

 
You can even write an extension function of Boolean.

2. Using compareTo() function

Alternatively, you can use the compareTo() to compare a Boolean instance with another and return an integer value.

3. Using hashCode() function

Another plausible but less recommended way involves using low-level bit manipulation with hash code value for the Boolean object. This works as the hashCode function consistently produces the same integer result for the same object.

4. Using length property

The trick here is to take advantage of the fact that the difference between the lengths of the string representation of the boolean values is 1. This approach is not recommended as this is not readable.

That’s all about converting a boolean to int in Kotlin.