0
0
Kotlinprogramming~5 mins

Constant values with const val in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does <code>const val</code> mean in Kotlin?
<p><code>const val</code> declares a compile-time constant. It means the value is fixed and known when the program is compiled, not changed at runtime.</p>
Click to reveal answer
beginner
Where can <code>const val</code> be used in Kotlin?
<p><code>const val</code> can only be used at the top level or inside an <code>object</code>. It cannot be used inside regular classes or functions.</p>
Click to reveal answer
intermediate
Why use <code>const val</code> instead of just <code>val</code>?
<p><code>const val</code> is a compile-time constant, so it can be inlined and used in annotations. <code>val</code> is a runtime constant and cannot be used in these cases.</p>
Click to reveal answer
beginner
Example: How to declare a constant string with <code>const val</code>?
<pre>object Constants {
    const val APP_NAME = "MyApp"
}</pre><p>This creates a constant string <code>APP_NAME</code> accessible as <code>Constants.APP_NAME</code>.</p>
Click to reveal answer
intermediate
Can <code>const val</code> hold complex objects or only primitives and strings?
<p><code>const val</code> can only hold primitive types (like <code>Int</code>, <code>Double</code>) and <code>String</code>. It cannot hold objects or types that require runtime initialization.</p>
Click to reveal answer
Which of the following is true about const val in Kotlin?
AIt is a compile-time constant and can be used in annotations.
BIt can be declared inside any function.
CIt can hold any object type.
DIt can be changed after initialization.
Where can you declare a const val in Kotlin?
AInside a regular class.
BInside a function.
CInside an <code>object</code> or at the top level.
DInside a <code>var</code> declaration.
What types of values can const val hold?
AOnly nullable types.
BOnly primitive types and strings.
COnly collections like lists or maps.
DAny object type.
Why might you choose const val over val?
ABecause <code>const val</code> values are known at compile time and can be inlined.
BBecause <code>const val</code> values are mutable.
CBecause <code>val</code> can only be used inside functions.
DBecause <code>val</code> cannot hold strings.
Which of these is a valid const val declaration?
Aconst val list = listOf(1, 2, 3)
Bconst val name = getName()
Cconst val user = User()
Dconst val PI = 3.14
Explain what const val means in Kotlin and where you can use it.
Think about when the value is fixed and where Kotlin allows this declaration.
You got /4 concepts.
    Describe the difference between const val and val in Kotlin.
    Consider when the value is known and how Kotlin treats each.
    You got /4 concepts.