Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean - Int conversion in Kotlin

Tags:

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?

like image 704
pavlos163 Avatar asked Sep 25 '17 09:09

pavlos163


People also ask

How do you convert boolean to Kotlin?

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.

How do you convert boolean to int?

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) ?

How do you use Boolean in Kotlin?

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.


2 Answers

You can write an extension function of Boolean like

fun Boolean.toInt() = if (this) 1 else 0 
like image 125
fweigl Avatar answered Oct 08 '22 15:10

fweigl


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 
like image 45
codegames Avatar answered Oct 08 '22 15:10

codegames