E05060: 'this()' and 'super()' can only be used in constructors, did you mean 'this.' or 'super.'

Category: E05xxx Explicit type symbol definition · Reported in phase: FULL_RESOLUTION · Classification: THIS_AND_SUPER_CALLS_ONLY_IN_CONSTRUCTOR · All error codes

What went wrong

You're using this() or super() as a CALL outside of a constructor. These are constructor delegation calls and are ONLY valid as the first statement inside a constructor body.

Worked examples

Compilable examples demonstrating this error and the correct fix:

  • ek9 -q 1311 (Why can't I call this() or super() inside a regular me...)

Syntax distinction

Constructor delegation (CALL) vs member access (DOT):

  • this() = call another constructor of THIS class (only in constructors)
  • this. = access member of this instance (anywhere in class)
  • super() = call parent constructor (only in constructors)
  • super. = access parent member (anywhere in class)

How to fix it

  1. If you meant to access a member: use 'this.' or 'super.' with DOT
  2. If you meant to delegate: move the call into a constructor
  3. Check if you confused call syntax () with access syntax .

Common causes

  • Confusing this() call with this. access
  • Copy-pasting constructor code into a regular method
  • Thinking super() can be used anywhere to call parent methods

See also

  • E05060: this()/super() in non-constructor context (this error)
  • E05050: delegation not first in constructor (ordering issue)
  • E05070: 'this' in context with no instance (function context)

Examples

Every example is compiled by the EK9 compiler: the first fails exactly as captioned, the others fix it.

Fails with E05060: 'this()' and 'super()' can only be used in constructors, did you mean 'this.' or 'super.'

#!ek9
defines module error.e05060.bad

  defines class

    Counter
      count as Integer: 0

      increment()
        count++

      reset()
        //this() constructs: it is only for the start of a constructor
        this()

      default operator ?

Fixed: Put shared work in a method; constructors delegate with this(...)

#!ek9
defines module error.e05060.good

  defines class

    Counter
      count as Integer: 0

      Counter()
        reset()

      Counter()
        -> start as Integer
        this()
        count: start

      increment()
        count++

      reset()
        count: 0

      default operator ?

Questions and answers

These Q&A entries show E05060 and its fix: