Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing == characters in scala

Tags:

scala

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 "("?

like image 963
cantdutchthis Avatar asked Apr 30 '14 19:04

cantdutchthis


People also ask

Can I use == to compare char?

Yes, char is just like any other primitive type, you can just compare them by == .

Can you compare strings in Scala?

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.


1 Answers

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
like image 141
lpiepiora Avatar answered Oct 10 '22 03:10

lpiepiora