E02040: variable name duplicated, resulting in multiple fields of same name

Category: E02xxx Symbol definition · Reported in phase: SYMBOL_DEFINITION · Classification: DUPLICATE_VARIABLE_IN_CAPTURE · All error codes

What went wrong

When creating a dynamic function or class, you're capturing the same variable multiple times. This would create duplicate fields.

Worked examples

Compilable examples demonstrating this error and the correct fix:

  • ek9 -q 115 (How do dynamic classes work in EK9?)

How to fix it

  • Remove the duplicate capture from the list
  • If you need multiple references, assign to different variables first

Common causes

  • Copy-paste error in capture list
  • Accidentally listing same variable twice

Note

Captured variables become fields in the dynamic class/function. Each field name must be unique.

See also

  • E02010: duplicate property/field
  • E50050: duplicate variable/constant

Examples

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

Fails with E02040: variable name duplicated, resulting in multiple fields of same name

#!ek9
defines module error.e02040.bad

  defines trait

    Validator
      validate()
        -> text as String
        <- result as Boolean?

  defines function

    discriminator() as abstract
      -> text as String
      <- rtn as Boolean?

  defines program

    CaptureTwice()
      min <- 10
      max <- 100

      //The same identifier captured twice
      longEnough <- (min, min) is discriminator as function
        rtn: length text > min

      //Two different values captured under one name
      validator <- (threshold: min, threshold: max) with trait of Validator as class
        override validate()
          -> text as String
          <- result as Boolean: length text > threshold

Fixed: Capture each variable once, and give every named capture its own name

#!ek9
defines module error.e02040.good

  defines trait

    Validator
      validate()
        -> text as String
        <- result as Boolean?

  defines function

    discriminator() as abstract
      -> text as String
      <- rtn as Boolean?

  defines program

    CaptureOnce()
      stdout <- Stdout()
      min <- 10
      max <- 100

      longEnough <- (min) is discriminator as function
        rtn: length text > min

      validator <- (minThreshold: min, maxThreshold: max) with trait of Validator as class
        override validate()
          -> text as String
          <- result as Boolean: length text > minThreshold and length text < maxThreshold
        default operator ?

      stdout.println($longEnough("a long enough sentence"))
      stdout.println($validator.validate("short"))

Questions and answers

These Q&A entries show E02040 and its fix: