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()
)
views:
310answers:
3You can do this easily with implicit conversions:
class asInt(b: Boolean) {
def toInt = if(b) 1 else 0
}
implicit def convertBooleanToInt(b: Boolean) = new asInt(b)
Then, you will get something like
scala> false toInt
res1: Int = 0
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
Actually, I'd expect it to be if (x) 1 else 0
, not if (x) 0 else 1
.
That's why you should write your own conversions. Integer isn't a boolean, and if you want for some reason to store booleans as integers, then you should hone your own standards of how the truth and not truth are represented.
Boolean "true" is not a number, it is an instance of the Boolean type. Like java.lang.Boolean.TRUE
. It can be stored internally as an integer, but that is an implementation detail that shouldn't be leaked into the language.
I'd say that if (x) 0 else 1
is the preferred method of conversion. It is simple and fast.
You can also write x match {case true => 0; case false => 1}
if you want to use a more general pattern matching approach.