Boolean - Int conversion to Kotlin

Is there a built-in way to convert between boolean-int in Kotlin? I am talking about the usual:

true -> 1 false -> 0 

If not, what is the idiomatic way to do this?

+15
kotlin
source share
5 answers

You can write an extension function like Boolean, for example

 fun Boolean.toInt() = if (this) 1 else 0 
+33
source share

You can extend Boolean with the extension property in this case:

 val Boolean.int get() = if (this) 1 else 0 

Now you can just do true.int in your code

+6
source share

Executing an API request that returns 0 or 1 for a field that must be explicitly true / false. At the same time, I also make other requests to similar APIs for the same type of fields, which will return true / false. I would like to share the code that processes this response from all APIs.

In this case, I think the best option would be to use the converter of your mapping library (jackson, etc.).

In simple Kotlin, you can use the extension / property function for this purpose.

+3
source share

There is no way to convert. you can convert by specifying the code below

  val output = if (input) 1 else 0 
+1
source share

use this one:

 val Boolean?.int get() = if (this != null && this) 1 else 0 
+1
source share

All Articles