Comparison Operators
Comparison operators ask questions like 'is this bigger?' or 'are these the same?' and answer true or false. It is like weighing two things on a scale.
In this page:
Syntax
a == b
a != b
a > b
a < b
a >= b
a <= b
Comparison Operators
Comparison operators (==, !=, >, <, >=, <=) compare two values and always produce a Boolean.
Unlike Java, Scala's == compares by value (calling .equals) for all types by default, not by reference -- so comparing two case class instances with equal fields works as expected. eq/ne are used when reference equality is specifically needed.
Note:
Scala's == is value equality by default for all types, unlike Java where == on objects compares references.
Example: Comparison Operators
object Main extends App {
val a = 5
val b = 8
println(a == b)
println(a != b)
println(a < b)
println(a >= 5)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
=instead of==for a comparison, which does not compile in a condition. - Using
eqto compare values, wheneqchecks reference identity and==checks equality. - Comparing values of unrelated types such as
5 == "5", which is always false.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: