Variable Declaration: val vs. var
In Kotlin, you explicitly choose between immutability and mutability at the moment of declaration. As an Engineering Manager, you should enforce a 'val-first' policy: always use val unless you are certain the value must change. This leads to safer, more predictable code in your concurrent Android modules.
- val (Value): Read-only references. Once assigned, the value cannot be changed. Equivalent to
finalin Dart. - var (Variable): Mutable references. The value can be reassigned multiple times during the app's lifecycle.
- Sound Null Safety
Kotlin's biggest strength is its built-in null safety. By default, variables cannot hold null values. To allow a variable to be null (e.g., a project description that might be empty), you must append a ? to the type. This matches the behavior you are used to in modern Dart.
- Advanced Initialization: lateinit and lazy
In complex Android components like Activities, you often can't initialize a variable at declaration. Kotlin provides two professional patterns for this:
- lateinit: Used for non-nullable variables that will be initialized later (e.g., in
onCreate). Use this for View references or dependency-injected services. - lazy: The variable is only initialized the first time it is accessed. This is perfect for heavy AI model loaders in Revochamp to save memory during startup.
Variable Comparison: Kotlin vs. Dart
| Feature | Kotlin | Dart (Flutter) |
|---|---|---|
| Read-only | val | final / const |
| Mutable | var | var |
| Null Safety | Type? (Explicit) | Type? (Explicit) |
| Deferred Init | lateinit | late |
| Lazy Load | by lazy { } | late (with assignment) |
| Type Inference | Supported | Supported |