cantdutchthis
cantdutchthis

Reputation: 34517

comparing == characters in 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 "("?

Upvotes: 12

Views: 16387

Answers (1)

lpiepiora
lpiepiora

Reputation: 13749

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

Upvotes: 33

Related Questions