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?
Convert String to Boolean You can use the toBoolean() to get the Boolean value represented by the specified string. The function returns true if the specified string is equal to “true” (case ignored) and false otherwise.
To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”. int val = (bool) ?
Kotlin Boolean ExpressionA Boolean expression returns either true or false value and majorly used in checking the condition with if...else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With