Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There an Easy Way to Convert a Boolean to an Integer?

I am new to scala and I am finding the need to convert a boolean value to an integer. I know i can use something like if (x) 1 else 0 but I would like to know if there is a preferred method, or something built into the framework (ie toInt())

like image 659
Russ Bradberry Avatar asked Apr 13 '10 22:04

Russ Bradberry


People also ask

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 change a boolean to an int in Python?

Use int for casting a Boolean value in Python. Using int() method will convert Boolean to Int, 1 for True and 0 for False.

How do you convert boolean to data?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.


1 Answers

If you want to mix Boolean and Int operation use an implicit as above but without creating a class:

implicit def bool2int(b:Boolean) = if (b) 1 else 0  scala> false:Int res4: Int = 0  scala> true:Int res5: Int = 1  scala> val b=true b: Boolean = true   scala> 2*b+1 res2: Int = 3 
like image 125
Patrick Avatar answered Sep 19 '22 17:09

Patrick