Boolean - Int conversion in 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


You can write an extension function of Boolean like

fun Boolean.toInt() = if (this) 1 else 0

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

Tags:

Kotlin