Why must certain operators return specific types in EK9?
← Code Quality · Ref: Q823
EK9 enforces strict return type rules for operators. Some operators must return the same type as the construct they belong to.
OPERATOR RETURN TYPE RULES
The ~ (negate/complement) operator must return the same type as the class:
MyNumber
operator ~ as pure
<- rtn as MyNumber // CORRECT: returns same type
Returning a different type triggers E07410:
MyNumber
operator ~ as pure
<- rtn as Float // ERROR: must return MyNumber
OTHER OPERATOR RULES
- Comparison operators (==, <>, <, >) must return Boolean
- The <=> (spaceship) operator must return Integer
- The #? (hashcode) operator must return Integer
- The $ (string) operator must return String
- The ~ (negate) operator must return the same construct type
See Q316 for operator semantics. See Q310 for code quality.
Example
defines module qa.quality.operator.return defines class Temperature degrees as Float: 0.0 Temperature() as pure -> initialDegrees as Float this.degrees :=: initialDegrees operator ~ as pure <- rtn as Temperature? negated <- 0.0 - degrees rtn: Temperature(negated) operator $ as pure <- rtn as String: $degrees default operator ? defines program OperatorReturnDemo() stdout <- Stdout() warm <- Temperature(25.0) cold <- ~warm stdout.println(`Warm: ${warm}`) stdout.println(`Negated: ${cold}`)
Common mistakes
E07410 — The ~ operator must return the same type as the class it belongs to; Temperature's ~ must return Temperature, not Float. See ek9 -h E07410 for details.
Incorrect:
operator ~ as pure <- rtn as Float? negated <- 0.0 - degrees rtn: negated
Correct:
operator ~ as pure <- rtn as Temperature? negated <- 0.0 - degrees rtn: Temperature(negated)
Other ways to ask this
- What is E07410 MUST_RETURN_SAME_AS_CONSTRUCT_TYPE?
- Why does my operator ~ return the wrong type?
- What are operator return type rules in EK9?
Coming from another language?
Java: operator overloading not supported (except + for String). C++: operator overloading has no return type enforcement. Rust: trait-based operators enforce return types via associated types. Python: __neg__ can return any type. EK9: compile-time return type enforcement for all operators.
Keywords: negate, construct, return, operator, complement, E07410, type