Why can't I use type inference inside a generic class body in EK9?

← Generics · Ref: Q854

Type inference with '<-' is not allowed inside generic/template class bodies. All types must be explicit because the type parameter T is unknown until instantiation.

See Q646 for type inference limits. See Q58 for generic functions.

Example

defines module qa.generics.no.inference

  defines class

    Container of type T

      default Container()

      default Container()
        -> item as T

      someMethod()
        someVar as Integer: 2
        require someVar?

  defines program

    GenericInferenceDemo()
      stdout <- Stdout()
      greeting <- "hello"
      stdout.println(greeting)

Common mistakes

E06070 — Type inference is not supported inside generic class bodies. Declare all types explicitly. See ek9 -h E06070 for details.

Incorrect:

        someVar <- 2

Correct:

        someVar as Integer: 2
Other ways to ask this
  • What triggers E06070 TYPE_INFERENCE_NOT_SUPPORTED?
  • Why does 'inferred <- 2' fail inside a generic class?
  • Why must all types be explicit in generic bodies?

Coming from another language?

Java: allows var inside generic bodies. Kotlin: allows inference everywhere. Rust: allows inference in generic impls. EK9: forbids all inference in generic bodies for consistency.

Keywords: explicit, generic, template, E06070, inference, type