Boolean - Int conversion in Kotlin
KotlinKotlin Problem Overview
Is there no built-in way to convert between boolean - int in Kotlin? I am talking about the usual:
true -> 1
false -> 0
If not, what is an idiomatic way to do it?
Kotlin Solutions
Solution 1 - Kotlin
You can write an extension function of Boolean like
fun Boolean.toInt() = if (this) 1 else 0
Solution 2 - Kotlin
writing a function for this task for every project can be a little tedious. there is a kotlin function that you can use it to achieve this.
with compareTo
if variable is greater than input it will output 1, if equal to it will output 0 and if less than input it will output -1
so you can use it for this task like this:
v.compareTo(false) // 0 or 1
Solution 3 - Kotlin
You could extend Boolean
with an extension property in this case:
val Boolean.int
get() = if (this) 1 else 0
Now you can simply do true.int
in your code
Solution 4 - Kotlin
> Making a request to an API that returns 0 or 1 for a field that should clearly be true/false. At the same time, I also make other requests to similar APIs for the same type of field that give me back true/false. I'd like to share the code that handles that response from all APIs.
In this case I think using converter of your mapping library (jackson, etc) will be best option.
In plain Kotlin you can use extension function/property for this purpose.
Solution 5 - Kotlin
No there is no way to convert. you only can convert by following below code
val output = if (input) 1 else 0
Solution 6 - Kotlin
use this :
val Boolean?.int
get() = if (this != null && this) 1 else 0