Difference Between const val and val in Kotlin

Difference Between const val and val in Kotlin

Kotlin provides two keywords, const val and val, for defining constants. While both are used to declare immutable values, there are significant differences between them in terms of usage, initialization, and behavior at runtime.

In this blog, we will break down these differences with examples to help you choose the right one for your use case.



Join our upcoming 6 Weeks Android Mentorship Program

Complete Syllabus




1. const val: Compile-Time Constants

The const val keyword is used to define compile-time constants. These constants are evaluated and assigned during compilation and cannot be changed at runtime.


Characteristics:

  • Must be a top-level declaration or defined in a companion object.
  • The value must be a primitive type (e.g., Int, Double, String) or a String literal.
  • Cannot use functions or expressions for initialization.
  • Can be inlined and directly substituted into the bytecode at compile time.


Example:

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

fun main() {
    println("API URL: $API_URL")
    println("Max Retry Count: $MAX_RETRY_COUNT")
}        

Bytecode Insight:

The const val value is replaced directly in the bytecode, making it faster and more efficient as no memory allocation occurs for the constant.


2. val: Runtime-Initialized Constants

The val keyword is used to declare read-only properties that are initialized at runtime. Once initialized, their value cannot be changed.


Characteristics:

  • Can be declared at any scope: top-level, inside a class, or in a function.
  • Can use complex expressions, function calls, or external data for initialization.
  • The initialization happens at runtime, and the value is stored in memory.


Example:

val currentTime: Long = System.currentTimeMillis()
val dynamicMessage: String = "Current time in milliseconds: $currentTime"

fun main() {
    println(dynamicMessage)
}        

Key Point:

Unlike const val, the value of val is not substituted at compile time but instead initialized when the code is executed.


3. When to Use const val vs. val


Use const val When:

  • You need compile-time constants for configurations or fixed values, like URLs, file paths, or constants used in annotations.
  • Example:


Use val When:

  • The value depends on runtime data, like timestamps, dynamic configurations, or results of function calls.
  • Example:


4. Common Misconceptions

  1. Can I use const val for non-primitive types?
  2. Is val immutable?
  3. Does const val improve performance?


Conclusion

Understanding the differences between const val and val is crucial for writing efficient and maintainable Kotlin code. Use const val for fixed compile-time constants and val for runtime-initialized, read-only properties. Choosing the right one ensures better performance and clarity in your code.



Join our upcoming 6 Weeks Android Mentorship Program

Complete Syllabus


Akshay Nandwana

Founder AndroidEngineers

You can connect with me on:



Book 1:1 Session

Join our upcoming classes

To view or add a comment, sign in

More articles by Akshay Nandwana 🇮🇳

  • 🚀 Jetpack Compose Cohort: May 1

    🚀 Jetpack Compose Cohort: May 1

    I'm thrilled to announce our upcoming intensive 7-day workshop designed to give you a hands-on, project-based journey…

  • Creating Magical Shared Element Transitions with Jetpack Compose

    Creating Magical Shared Element Transitions with Jetpack Compose

    Hi Android enthusiasts! Have you ever admired the beautiful animations when navigating between screens in apps like…

    1 Comment
  • Infix Notation in Kotlin

    Infix Notation in Kotlin

    Kotlin provides many features that enhance the readability and expressiveness of code. One such feature is infix…

  • Mastering Coding Patterns in Kotlin

    Mastering Coding Patterns in Kotlin

    As an Android Kotlin developer, understanding coding patterns is essential for writing clean, efficient, and scalable…

    2 Comments
  • Analytics Logging System in NowInAndroid App

    Analytics Logging System in NowInAndroid App

    This blog will walk you through the step-by-step process of building a scalable and testable analytics logging…

    1 Comment
  • lateinit vs lazy in Kotlin

    lateinit vs lazy in Kotlin

    Kotlin offers two ways to initialize properties lazily: and . While both are used to delay initialization, they serve…

    3 Comments
  • GSoC Orgs for Android Enthusiasts 🚀

    GSoC Orgs for Android Enthusiasts 🚀

    🚀 Looking to contribute to Android-related projects and be part of Google Summer of Code (GSoC)? Here’s a curated list…

    1 Comment
  • Design Patterns in Android Development

    Design Patterns in Android Development

    Design patterns are proven solutions to common problems in software design. They help structure code, improve…

  • Mastering LRU Cache in Kotlin

    Mastering LRU Cache in Kotlin

    As a Senior Engineer, I’ve found that mastering algorithms isn’t just about memorizing their definitions but truly…

  • Android Engineer Interview Questions

    Android Engineer Interview Questions

    Kotlin Difference Between const val and val? Answer What is Data Class in Kotlin? What are the different Coroutine…

    3 Comments

Insights from the community

Others also viewed

Explore topics