0
0
Kotlinprogramming~5 mins

Constant values with const val in Kotlin

Choose your learning style9 modes available
Introduction

We use const val to create values that never change. This helps keep our program safe and clear.

When you have a value like Pi that should stay the same everywhere.
When you want to name a fixed number like the maximum score in a game.
When you need a constant string like a URL or a key name.
When you want to avoid repeating the same value in many places.
When you want to make your code easier to read and maintain.
Syntax
Kotlin
const val NAME: Type = value

const val must be used at the top level or inside an object.

The value must be known at compile time (like numbers or strings).

Examples
This creates a constant integer named MAX_SCORE with value 100.
Kotlin
const val MAX_SCORE: Int = 100
This creates a constant string named BASE_URL with a website address.
Kotlin
const val BASE_URL: String = "https://example.com"
You can group constants inside an object for better organization.
Kotlin
object Constants {
    const val PI: Double = 3.14159
}
Sample Program

This program prints a greeting and the value of PI stored as constants.

Kotlin
const val GREETING: String = "Hello, friend!"

fun main() {
    println(GREETING)
    println("The value of PI is approximately " + Constants.PI)
}

object Constants {
    const val PI: Double = 3.14159
}
OutputSuccess
Important Notes

You cannot change a const val after it is set.

const val is different from val because val can be assigned at runtime, but const val must be known when the program is compiled.

Use const val for simple values like numbers and strings only.

Summary

const val creates fixed values that never change.

They must be simple types and known when the program is built.

Use them to make your code safer and easier to understand.