views:

310

answers:

3

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

+10  A: 

You 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
Jackson Davis
The library convention is to use `toInt`--the same would be a good idea here.
Rex Kerr
fair enough, edited to reflect that.
Jackson Davis
This great technique is called "pimp my library".
David Crawshaw
+7  A: 

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
Patrick
what are the advantages of using implicit without a class?
Russ Bradberry
@Russ Bradberry, If you try the answer from @Jackson Davis you have to call explicitely the function asInt to do the conversion so doing ==> val a:Int=true is not possible, and so doing ==> (1-true). The conversion is not transparent.
Patrick
so does this make it global? or do i need to do something special to make this global? also, will this work as something like if I insert into mysql `"insert into blah (boolVal) values (" + b + ")"`, will it automatically assume its the int version and not the bool version?
Russ Bradberry
@Russ Bradberry. No in your case you concatanate a String with a Boolean so there is no way that the compiler figure out that you want an Int instead of the Boolean. You can cast the value to an Int : `"insert into blah (boolVal) values (" + (b:Int) + ")"`
Patrick
@Russ Bradberry it is not global, you can put your implicits into an object and then import them whenever you need todo some conversion
Patrick
+2  A: 

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.

ArtemGr
well the idea was to convert it to the c standard 0=false, 1=true. But why would i use match rather than the ternary if else?
Russ Bradberry