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