Overview of comparisons

In general, the comparison operators work as you might expect if you are familiar with most programming languages. Some notable differences are:

  • The operators >, <, >=, and <= operators work with all objects that implement the Comparable interface, not just with numbers.
  • The standard equal comparison == operator implicitly uses the equals method on the first (leftmost) object. This operator does not check for pointer equality. It is null safe in that if the value on either side of the operator is null, Gosu does not throw a null pointer exception.
    Note: In contrast, in the Java language, the == operator evaluates to true if and only if both operands have exactly the same reference value. The Java expression evaluates to true if both terms refer to the same object in memory. This behavior provides the expected result for primitive types like integers. For reference types, the references are not usually what you want to compare. Instead, to compare value equality, Java code typically uses object.equals(), rather than the == operator.
  • In some cases, you do need to compare identity references, to determine whether two objects reference the same in-memory object. Gosu provides a special equality operator called === (three equal signs) to compare object equality. This operator compares whether both references point to the same in-memory object. The following examples illustrate some differences between == and === operators:

Expression

Output

Description

var x = 1 + 2

var str = x as String

print(str == "3")

true

These two comparison arguments reference the same value but different objects. Using the double-equals operator returns true.

var x = 1 + 2

var str = x as String

print(str === "3")

false

These two comparison arguments reference the same value but different objects. Using the triple-equals operator returns false.

See also