What does 'this' mean in a function in EK9, and what triggers E05070?

← Classes and OOP · Ref: Q787

In a class, record or component, 'this' refers to the current object instance, so methods, operators and constructors can write this.count.

THIS IN A FUNCTION

'this' is also valid in a function, but there it means the function object itself, not an instance with fields. So 'me <- this' compiles in a function, while 'this.count' in a function is E50001 (not resolved): a function has no fields.

WHAT IS ACTUALLY REJECTED

- this() in a function: E05070 (inappropriate use of 'this'). A function has no constructors to delegate to.
- this() or super() in a class method (not a constructor): E05060. Constructor delegation is only valid inside a constructor.
- Direct assignment to this (this := Counter()): E05090. 'this' can be used with :=:, :~:, +=, -=, /= and *=, but not direct assignment.

THIS EXAMPLE

The Counter class uses this.count in its methods - valid because methods run on an instance with that field. The standalone increment() function has no fields, so it works from its parameter 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: in class/record/component members this is the instance; in a function this is the function object (no fields, so this.field is E50001); this() outside a constructor is E05070 (function) or E05060 (method).

Keywords: E05070, method, scope, instance, function, class, stateless, this