Bird
0
0

Which of the following is the best way to declare it to ensure it is a compile-time constant accessible everywhere?

hard📝 Application Q15 of 15
Kotlin - Variables and Type System
You want to create a constant string APP_NAME that can be used throughout your Kotlin app. Which of the following is the best way to declare it to ensure it is a compile-time constant accessible everywhere?
ADeclare <code>const val APP_NAME = "MyApp"</code> at the top level or inside an object
BDeclare <code>val APP_NAME = "MyApp"</code> inside main() function
CDeclare <code>var APP_NAME = "MyApp"</code> inside a class constructor
DDeclare <code>const var APP_NAME = "MyApp"</code> inside a class
Step-by-Step Solution
Solution:
  1. Step 1: Understand where const val can be declared

    In Kotlin, const val must be declared at the top level or inside an object to be a compile-time constant accessible everywhere.
  2. Step 2: Evaluate each option

    Declare const val APP_NAME = "MyApp" at the top level or inside an object correctly declares const val APP_NAME = "MyApp" at the top level or inside an object. Declare val APP_NAME = "MyApp" inside main() function uses val inside a function, which is not compile-time constant. Declare var APP_NAME = "MyApp" inside a class constructor uses var which is mutable. Declare const var APP_NAME = "MyApp" inside a class uses invalid syntax const var.
  3. Final Answer:

    Declare const val APP_NAME = "MyApp" at the top level or inside an object -> Option A
  4. Quick Check:

    const val + top-level/object = global constant [OK]
Quick Trick: const val must be top-level or in object for global constant [OK]
Common Mistakes:
MISTAKES
  • Declaring const val inside functions
  • Using var with const keyword
  • Using const without val

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes