Convert a boolean to int in Kotlin
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.
|
1 2 3 |
fun booleanToInt(b: Boolean): Int { return if (b) 1 else 0 } |
You can even write an extension function of Boolean.
|
1 |
fun Boolean.toInt() = if (this) 1 else 0 |
2. Using compareTo() function
Alternatively, you can use the compareTo() to compare a Boolean instance with another and return an integer value.
|
1 2 3 |
fun booleanToInt(b: Boolean): Int { return b.compareTo(false) } |
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.
|
1 2 3 |
fun booleanToInt(b: Boolean?): Int { return 1 and (b.hashCode() shr 1) } |
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.
|
1 2 3 4 |
// returns 1 for true and 0 for false fun booleanToInt(b: Boolean): Int { return "false".length - b.toString().length } |
That’s all about converting a boolean to int in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)