有一种简单的方法可以将布尔值转换为整数吗? [英] Is There an Easy Way to Convert a Boolean to an Integer?

查看:197
本文介绍了有一种简单的方法可以将布尔值转换为整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是scala的新手,我发现需要将布尔值转换为整数。我知道我可以使用类似的东西if(x)1 else 0 但是我想知道是否有一个首选方法,或者框架中内置的东西(即 toInt()

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

推荐答案

如果你想混合 Boolean Int 操作使用隐式,但不创建类:

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

这篇关于有一种简单的方法可以将布尔值转换为整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆