How do I check if two colours are equal and convert a colour to its string representation?

← Operators and Expressions · Ref: Q1190

EK9 Colour uses hex literals (#RRGGBB) and supports equality, comparison, and string conversion operators.

COLOUR LITERALS

  primary <- #FF0000       red
  other <- #FF0000         same red
  accent <- #00FF00        green

EQUALITY

  if primary == other          same colour
  if primary <> accent         different colour

STRING CONVERSION

  str <- $primary              converts to string representation

COMPARISON

  ordering <- primary <=> accent  spaceship comparison
  brighter <- primary >? accent   coalescing for greater

Colour also supports arithmetic (+ for blend, - for remove) and HSL manipulation (withHue, withSaturation, withLightness). Use 'ek9 -h Colour' for the full API.

See Q34 for Colour basics. See Q238 for the complete operator set.

Example

defines module qa.operators.colourequality

  defines program

    ColourEqualityDemo()
      stdout <- Stdout()

      // === COLOUR LITERALS ===

      primary <- #FF0000
      other <- #FF0000
      accent <- #00FF00
      highlight <- #0000FF

      // === EQUALITY ===

      if primary == other
        stdout.println("Primary and other are the same colour")

      require primary == other
      require primary <> accent
      require accent <> highlight

      // === SPACESHIP ORDERING ===

      ordering <- primary <=> accent
      stdout.println(`Red <=> Green: ${ordering}`)

      // === STRING CONVERSION ===

      redStr <- $primary
      greenStr <- $accent
      stdout.println(`Red as string: ${redStr}`)
      stdout.println(`Green as string: ${greenStr}`)

      // === COALESCING ===

      lesser <- primary <? accent
      greater <- primary >? accent
      stdout.println(`Lesser colour: ${lesser}`)
      stdout.println(`Greater colour: ${greater}`)

      // === ISSET ===

      require primary?
      unsetColour <- Colour()
      require ~unsetColour?

      // === COPY ===

      copied <- Colour()
      copied :=: primary
      require copied == primary
      stdout.println(`Copied colour: ${copied}`)

Common mistakes

E50060 — Colour has no equals() method. EK9 uses the == operator for equality checks on all types. See ek9 -h E50060 for details.

Incorrect:

if primary.equals(other)

Correct:

if primary == other
Other ways to ask this
  • Compare two Colour values for equality in EK9.
  • I need to verify whether a pixel matches a target colour.
  • In CSS I compare hex codes as strings — how does EK9 compare colours?

Coming from another language?

Java: java.awt.Color.equals(), getRGB() for comparison. Python: no built-in, tuple comparison. CSS: string comparison of hex codes. JavaScript: no built-in colour type. EK9: #RRGGBB literals, direct == <> operators, $ for string, arithmetic blending.

Keywords: rgb, match, colour, color, equality, conversion, string, compare, operator, hex