Why does EK9 require an explicit constructor when properties are uninitialized?
← Classes and OOP · Ref: Q769
EK9 requires that every property has a known value before use. When you declare a property as unset (using 'as Type?' instead of '<- value'), the compiler cannot auto-generate a constructor because it does not know what values to assign.
TWO PROPERTY STYLES
1. Initialised: 'name <- "default"' — value known, default constructor works
2. Uninitialised: 'name as String?' — value unknown, explicit constructor REQUIRED
THIS EXAMPLE
The User class initialises both properties with '<-'. This allows 'default operator ?' and no explicit constructor is needed. The mutation removes the initialisation, creating an uninitialised property that triggers E07170.
WHY THIS RULE EXISTS
Java allows null fields with no warning. This causes NullPointerException at runtime when fields are used before being set. EK9 moves this check to compile time — if a property has no value, you must provide a constructor that gives it one.
HOW TO FIX
1. Initialise the property at declaration: 'name <- "unknown"'
2. Or provide an explicit constructor that sets it
See Q93 for defining classes. See Q89 for constructors. See Q99 for why explicit constructors matter.
Example
defines module qa.classesandoop.explicitconstructor defines class User name <- String() active <- true describe() <- rtn as String: `${name} active=${active}` default operator ? Item title <- String() count <- 0 getTitle() <- rtn as String: title default operator ? defines program ShowUser() stdout <- Stdout() user <- User() if user? stdout.println(user.describe()) item <- Item() if item? stdout.println(item.getTitle())
Common mistakes
E07170 — Changing 'name <- String()' (initialised) to 'name as String?' (uninitialised) means the compiler cannot generate a default constructor. Either initialise the property or add an explicit constructor that sets it. See ek9 -h E07170 for details.
Incorrect:
name as String?
Correct:
name <- String()
E07170 — Changing initialised property to uninitialised requires an explicit constructor. Without one, the compiler cannot ensure the property has a value before use. See ek9 -h E07170 for details.
Incorrect:
title as String?
Correct:
title <- String()
Other ways to ask this
- What triggers E07170 explicit constructor required?
- How do I fix uninitialised property errors in EK9?
- Why can't I declare a property without a value in EK9?
Coming from another language?
Java: fields default to null/0, no compile-time enforcement. Python: __init__ sets fields, no enforcement for completeness. Rust: all struct fields must be initialised at creation, no partial init. Kotlin: lateinit defers but crashes at runtime if used before init. Go: zero values for all fields. EK9: uninitialised properties require explicit constructor — compile-time enforcement.
Keywords: property, explicit, field, required, class, null, constructor, uninitialised, E07170, initialise