Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 19 / 68

Constants (const val)

In this lesson you will learn how to declare constants with const val in Kotlin, so values that must not change are handled safely. This is for anyone searching for "Kotlin const val how to use".

const val creates a constant whose value cannot be changed later. Its value has to be known at compile time, and it is usually written outside any function, at the top level.

The sample code defines a perfect score as a constant with const val MAX_SCORE = 100 and uses it to build a message. Writing a constant name in capitals with underscores, as in MAX_SCORE, is a convention shared with many languages.

A common stumbling block for beginners is the difference between val and const val. A plain val also cannot be changed at run time, but const val means a stricter constant whose value is fixed at compile time.

In real-world development, constants are a basic technique for avoiding magic numbers and communicating the intent of your code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)