在 scala 中,将 Int 7 与 char '7' 进行比较会给出 false
in scala, comparing Int 7 with char '7' gives false
为什么以下表达式的计算结果为 false
?
scala> 7 == '7'
res0: Boolean = false
scala> 7.toChar == '7'
res1: Boolean = false
scala> 7.toChar equals '7'
res2: Boolean = false
比较数字和字符的正确方法是什么?
我的问题是我有以下 Map[Char, Int]()
,
Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
和
map getOrElse(7.toChar, 0)
returns0
。我希望结果为 2
,因为我的地图包含 2 -> 7
.
Why do the following expressions evaluate to false
?
scala> 7 == '7'
res0: Boolean = false
The numeric value of the character '7'
is 55
、55
不等于 7
,因此,表达式的计算结果为 false
.
scala> 7.toChar == '7'
res1: Boolean = false
scala> 7.toChar equals '7'
res2: Boolean = false
The character value of the number 7
is the BEL
character,不是字符 '7'
,因此,这两个表达式的计算结果为 false
.
What is the correct way to compare number with characters?
My problem is that I have the following Map[Char, Int]()
,
Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
字符 7
的 Scala 字符文字是 '7'
,因此您可以直接使用它:
map getOrElse('7', 0)
// => 2
如果出于某种原因,您只有数字 7
可用,最简单 的方法是将您的 Map
更改为地图数字到数字:
val map = Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
map getOrElse(7, 0)
// => 2
如果您做不到,那么您真正想要的是所讨论数字的字符串表示形式产生的字符,而不是数字的字符值:
map getOrElse(7.toString.charAt(0), 0)
// => 2
为什么以下表达式的计算结果为 false
?
scala> 7 == '7'
res0: Boolean = false
scala> 7.toChar == '7'
res1: Boolean = false
scala> 7.toChar equals '7'
res2: Boolean = false
比较数字和字符的正确方法是什么?
我的问题是我有以下 Map[Char, Int]()
,
Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
和
map getOrElse(7.toChar, 0)
returns0
。我希望结果为 2
,因为我的地图包含 2 -> 7
.
Why do the following expressions evaluate to
false
?scala> 7 == '7' res0: Boolean = false
The numeric value of the character '7'
is 55
、55
不等于 7
,因此,表达式的计算结果为 false
.
scala> 7.toChar == '7' res1: Boolean = false scala> 7.toChar equals '7' res2: Boolean = false
The character value of the number 7
is the BEL
character,不是字符 '7'
,因此,这两个表达式的计算结果为 false
.
What is the correct way to compare number with characters?
My problem is that I have the following
Map[Char, Int]()
,Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
字符 7
的 Scala 字符文字是 '7'
,因此您可以直接使用它:
map getOrElse('7', 0)
// => 2
如果出于某种原因,您只有数字 7
可用,最简单 的方法是将您的 Map
更改为地图数字到数字:
val map = Map(7 -> 2, 1 -> 1, 5 -> 1, 0 -> 1)
map getOrElse(7, 0)
// => 2
如果您做不到,那么您真正想要的是所讨论数字的字符串表示形式产生的字符,而不是数字的字符值:
map getOrElse(7.toString.charAt(0), 0)
// => 2