比较 Scala 中的 == 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23396118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:14:26  来源:igfitidea点击:

comparing == characters in scala

scala

提问by cantdutchthis

I am trying to teach myself some scala. And I am stuck with something that seems arbitrary. I want to compare weather two characters are equal to each other.

我正在尝试自学一些 Scala。我被一些看似随意的东西困住了。我想比较两个字符是否相等的天气。

True example

真实例子

These return true as expected

这些按预期返回 true

"(" == "(" 
"(".equals("(")

What I want to check

我想检查什么

"(an exampl(e))".toList(0)      // res : Char = (

Somehow false

不知何故是假的

These return false

这些返回假

"(an exampl(e))".toList(0).equals("(")
"(an exampl(e))".toList(0) == "("   
"(an exampl(e))".toList.head == "("  

I think I am missing something here. Am I comparing the character value to a list pointer? If so, how can I check that the value of the item that I am pointing to is equal to "("?

我想我在这里遗漏了一些东西。我是否将字符值与列表指针进行比较?如果是这样,我如何检查我指向的项目的值是否等于"("

回答by lpiepiora

Short answer is You should compare with ')' not ")". The ")" is of type Stringnot Char.

简短的回答是你应该与')'而不是")"进行比较。")" 的类型为Stringnot Char

Using REPL, you can easily test it (note the type).

使用 REPL,您可以轻松测试它(注意类型)。

scala> ')'
res0: Char = )

scala> ")"
res1: String = )

The equals method is defined more or less like this equals(obj: Any): Boolean, so the code compiles doesn't matter what reference you pass to it as an argument. However the check is false, as the type is not the same.

equals 方法或多或少是这样定义的equals(obj: Any): Boolean,因此代码编译并不重要,您将什么引用作为参数传递给它。但是检查是false,因为类型不一样。

By the way I think nicer way is to write your tests like this (without .toListas .headis defined in StringOpsas well):

顺便说一句,我认为更好的方式是写你的测试是这样的(不.toList.head被定义StringOps为好):

scala> "(an exampl(e))".head == '('
res2: Boolean = true