android-kotlin
/

Kotlin Variables – Immutability and Type Safety

Last Sync: Today

On this page

4
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

android-kotlin

Kotlin Variables – Immutability and Type Safety

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 final in Dart.
  • var (Variable): Mutable references. The value can be reassigned multiple times during the app's lifecycle.
KOTLINRead-only
1
// Type inference is supported
val projectId = "revo_772" 
var widgetCount = 0

// Explicit typing (if needed)
val version: Double = 2.0

widgetCount = 1 // OK
// projectId = "new_id" // Compilation Error

  1. 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.

KOTLINRead-only
1
var name: String = "Kishore" 
// name = null // Error

var bio: String? = null // Nullable

// Safe access using ?. (Safe Call)
println(bio?.length)

// Elvis operator (?:) for default values
val bioLength = bio?.length ?: 0

  1. 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.
KOTLINRead-only
1
// Late initialization
lateinit var apiClient: RevoApiClient

// Lazy initialization (only runs when 'config' is used)
val config: String by lazy {
    println("Loading heavy config file...")
    "AI_MODEL_V1_SETTINGS"
}

Variable Comparison: Kotlin vs. Dart

FeatureKotlinDart (Flutter)
Read-onlyvalfinal / const
Mutablevarvar
Null SafetyType? (Explicit)Type? (Explicit)
Deferred Initlateinitlate
Lazy Loadby lazy { }late (with assignment)
Type InferenceSupportedSupported

Test Your Knowledge

Q1
of 3

Which keyword is used to declare a variable that can be reassigned?

A
val
B
var
C
let
D
const
Q2
of 3

What is the correct way to declare a String variable that can hold a null value?

A
String name = null
B
var name: String!
C
var name: String?
D
val name: String
Q3
of 3

Which initialization pattern should be used for a heavy object that should only load when it is actually needed?

A
lateinit
B
var
C
by lazy
D
init

Frequently Asked Questions

What is the difference between val and const val?

'val' is a runtime constant (assigned while the app is running), while 'const val' is a compile-time constant. 'const val' can only be used at the top level or inside an object, and is used for values that never change, like API versions or base URLs.

Can I use 'lateinit' with primitive types like Int or Boolean?

No. 'lateinit' only works with reference types (classes). For primitives, you should use a standard nullable type or a default value.

Does Kotlin have 'dynamic' like Dart?

Kotlin has 'Any', which is the root of the type hierarchy (like Object in Java). However, it is not dynamic; you must cast it to a specific type before calling methods on it, ensuring strict type safety.

Previous

kotlin syntax

Next

kotlin control flow

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.