Difference Between val and const in Kotlin

1. Introduction

In Kotlin, val and const are both used to declare variables that cannot be reassigned after initialization, but they have distinct characteristics and uses. The val keyword declares a read-only property or local variable. Meanwhile, const is used to define compile-time constants, meaning the value of a const variable is known at compile time and cannot be changed.

2. Key Points

1. Mutability: Both val and const are immutable, but val can have a custom getter with varying values.

2. Initialization: const must be initialized with a value known at compile time, val can be initialized with a runtime expression.

3. Usage Scope: const can only be used at the top level or in an object declaration, not in a class. val can be used anywhere.

4. Type Restrictions: const only allows primitives and String types, while val has no such restriction.

3. Differences

Characteristic Val Const
Mutability Immutable with a custom getter Immutable, no custom getter
Initialization Runtime expression Compile-time expression
Usage Scope Anywhere Top-level or in an object
Type Restrictions No restrictions Primitives and String

4. Example

// Example of Val
val pi: Double
    get() = 3.14

// Example of Const
const val MAX_COUNT = 100

Output:

Val Output:
pi will return 3.14 when accessed
Const Output:
MAX_COUNT will always be 100

Explanation:

1. pi is a val with a custom getter, allowing for complex logic. Its value is determined at runtime.

2. MAX_COUNT is a const, which means its value is set at compile time and cannot be changed.

5. When to use?

- Use val for read-only properties that might require complex initialization or a custom getter.

- Use const for defining constants that are primitives or Strings, whose value you know at compile time and that are not tied to a class instance.

Comments