Russ Bradberry Russ Bradberry - 1 year ago 113
Scala Question

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download