Why can't I use 'this' in a function in EK9?
← Classes and OOP · Ref: Q787
The 'this' keyword refers to the current object instance. It only exists inside class methods, constructors, and operators — places where an object instance is available.
WHERE THIS IS VALID
- Class methods and operators (refers to the class instance)
- Record operators (refers to the record instance)
- Component methods (refers to the component instance)
- Constructors (refers to the object being created)
WHERE THIS IS NOT VALID
- Functions (stateless, no instance)
- Programs (not an object)
- Module-level code
THIS EXAMPLE
The Counter class uses this.count in its methods — valid because methods have an instance. The standalone increment() function has no instance, so it uses parameters instead.
See Q50 for functions vs methods. See Q93 for class basics.
Example
defines module qa.classesandoop.thisinkclasses defines function increment() as pure -> current as Integer <- rtn as Integer: current + 1 defines class Counter count <- Integer() Counter() -> initial as Integer count :=: initial next() count: this.count + 1 current() <- rtn as Integer: this.count default operator ? defines program ShowCounter() stdout <- Stdout() counter <- Counter(0) counter.next() counter.next() stdout.println($counter.current()) result <- increment(10) stdout.println($result)
Common mistakes
E05070 — Using this() in a function attempts constructor delegation, but functions have no constructors. The this() call is only valid inside a class constructor. See ek9 -h E05070 for details.
Incorrect:
<- rtn as Integer: current + 1 copy <- this()
Correct:
<- rtn as Integer: current + 1
Other ways to ask this
- What triggers E05070 inappropriate use of this?
- Where is the this keyword valid in EK9?
- Why does my function reject this.field?
Coming from another language?
Java: this available in all instance methods, not in static methods. Python: self is an explicit parameter (same concept). Rust: self/&self parameter in impl methods. Kotlin: this available in class members. Go: receiver parameter serves as this. EK9: this only in class/record/component methods and constructors, never in functions.
Keywords: instance, scope, method, E05070, this, stateless, class, function