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.
True example
These return true as expected
"(" == "("
"(".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 "("?
Yes, char is just like any other primitive type, you can just compare them by == .
In Scala, the == method defined in the AnyRef class first checks for null values, and then calls the equals method on the first object (i.e., this ) to see if the two objects are equal. As a result, you don't have to check for null values when comparing strings.
Short answer is You should compare with ')' not ")". The ")" is of type String not Char.
Using REPL, you can easily test it (note the type).
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.
By the way I think nicer way is to write your tests like this (without .toList as .head is defined in StringOps as well):
scala> "(an exampl(e))".head == '('
res2: Boolean = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With