KotlinIntermediate4 min
Difference Between const val and val?

Additional Resources

Answer

Both const val and val are used to declare immutable (read-only) properties in Kotlin, but they differ in when and how their values are determined.


const val - Compile-Time Constants


const val declares compile-time constants whose values must be known during compilation.


Requirements:

  • Must be declared at top-level, inside an object, or in a companion object
  • Can only be primitive types (Int, Double, Boolean) or String
  • Cannot be assigned from function calls or complex expressions
  • - Value is inlined into bytecode at compile-time for better performance


    const val API_URL = "https://api.example.com" // Valid

    const val MAX_RETRY = 3 // Valid

    const val TIME = System.currentTimeMillis() // Invalid - function call



    val - Runtime Constants


    val declares runtime constants that are initialized when the code executes.


    Characteristics:

  • Can be declared anywhere (top-level, inside classes, functions)
  • Supports any data type and complex expressions
  • Can use function calls and custom getters
  • Value is stored in memory and accessed at runtime

  • val currentTime = System.currentTimeMillis() // Valid - runtime initialization

    val userName = getCurrentUser() // Valid - function call

    val config: String

    get() = if (isDev) "dev" else "prod" // Valid - custom getter



    When to Use Which?


    Use const val for:

  • Fixed configuration values, API URLs, constants
  • Values that never change and are known beforehand
  • Better performance due to compile-time inlining[5]

  • Use val for:

  • Values determined at runtime (timestamps, user input)
  • Function results or complex calculations
  • Any scenario requiring runtime flexibility

  • Key Difference


    The main distinction is timing: const val is evaluated at compile-time and inlined for performance, while val is evaluated at runtime and stored in memory.


    Share This Question