Const

Beginner Level

1. What is the const keyword in Kotlin?

Answer:

In Kotlin, const is used to declare compile-time constants. These are values that are determined at compile time and cannot be changed at runtime.

Example:

kotlin
const val APP_NAME = "DayaMed" const val MAX_USERS = 100

✅ Key Points:

  • const val can only be used inside top-level declarations or inside object or companion object.
  • The value must be known at compile time.

2. What is the difference between const val and val in Kotlin?

Featureconst valval
MutabilityImmutable (cannot change)Immutable (but can be assigned dynamically)
InitializationMust be initialized with a compile-time constantCan be initialized with a runtime value
UsageOnly in top-level, object, or companion objectCan be used anywhere (class, function, etc.)
Exampleconst val MAX = 10val max = getMaxValue()

Example:

kotlin
const val VERSION = "1.0" // ✅ Allowed val dynamicVersion = System.getenv("APP_VERSION") // ❌ Not allowed as const

✅ Key Takeaway:

  • const val is resolved at compile time.
  • val can be assigned at runtime.

3. Where can const val be used in Kotlin?

Answer:

  • Top-level in a Kotlin file ✅
  • Inside object or companion object ✅
  • Inside a regular class (as a member variable) ❌ (Not allowed!)

Example:

kotlin
object Config { const val BASE_URL = "https://api.dayamed.com" } class MyClass { // const val MY_VALUE = "Hello" // ❌ ERROR: Cannot use `const` in a regular class }

4. Can const be used with non-primitive types?

Answer:

No. const val only supports primitive types like StringIntDoubleBooleanLongFloat, and Char.

✅ Allowed:

kotlin
const val TIMEOUT = 5000 const val APP_NAME = "DayaMed"

❌ Not Allowed:

kotlin
// const val colors = listOf("Red", "Blue", "Green") // ERROR // const val user = User("John", 25) // ERROR

✅ Key Takeaway:

  • const cannot be used with collections, objects, or functions.

Intermediate Level

5. What is the difference between const val and companion object?

Answer:

Featureconst valcompanion object
AccessDirectly accessibleNeeds class reference
UsageCompile-time constants onlyCan hold runtime logic
Exampleconst val MAX = 10companion object { val max = getMaxValue() }

Example:

kotlin
const val API_KEY = "12345" // Directly accessible class AppConfig { companion object { val maxRetries = 3 // Needs `AppConfig.maxRetries` } }

✅ Key Takeaway:

  • Use const val for static constants.
  • Use companion object for static runtime values.

6. Can const val be used inside a function?

Answer:

No. const val cannot be declared inside a function because it must be resolved at compile time.

❌ Invalid Example:

kotlin
fun getConfig() { // const val ERROR_MESSAGE = "Error occurred" // ❌ ERROR }

✅ Solution: Declare const val at the top-level or inside an object.

kotlin
const val ERROR_MESSAGE = "Error occurred" // ✅ Works

7. Can const val be used in an interface?

Answer:

Yes! Since interface properties are implicitly abstract, they cannot hold values. However, const val is allowed inside interfaces because it is a compile-time constant.

Example:

kotlin
interface Constants { companion object { const val APP_VERSION = "2.1.0" } } fun main() { println(Constants.APP_VERSION) // ✅ Output: 2.1.0 }

✅ Key Takeaway:

  • const val can be inside an interface using a companion object.

Advanced Level

8. How does const val work in decompiled Java code?

Answer:

Kotlin's const val is treated as a static final field in Java.

Example:

kotlin
const val APP_NAME = "DayaMed"

➡ Decompiled Java Code:

java
public final class ConstantsKt { public static final String APP_NAME = "DayaMed"; }

✅ Key Takeaway:

  • const val behaves like a public static final field in Java.

9. What is the difference between const val and static final in Java?

Featureconst val (Kotlin)static final (Java)
AccessDirectly accessibleNeeds ClassName.FIELD
Typeval onlyCan be any type
InitializationCompile-time onlyCan be set in static block

✅ Kotlin

kotlin
const val TIMEOUT = 5000

✅ Equivalent Java

java
public static final int TIMEOUT = 5000;

✅ Key Takeaway:

  • Kotlin const val is a direct replacement for static final in Java.

10. Real-World Example: Using const val for API Configuration

Scenario: You need static API keys for network requests.

kotlin
object ApiConfig { const val BASE_URL = "https://api.dayamed.com" const val API_KEY = "abcd1234" }

✅ Usage:

kotlin
val url = ApiConfig.BASE_URL

🚀 Benefit: No function calls, better performance!


11. Real-World Example: Using const val for Intent Extras

Scenario: You need constant keys for passing data between activities.

kotlin
object IntentKeys { const val USER_ID = "extra_user_id" const val USER_NAME = "extra_user_name" }

✅ Usage:

kotlin
val intent = Intent(this, UserDetailsActivity::class.java).apply { putExtra(IntentKeys.USER_ID, 123) }

🚀 Benefit: Prevents hardcoded strings and typos!


12. When should you use const val vs enum class?

Featureconst valenum class
UsageSimple constantsGroup of related values
PerformanceFaster, no object creationSlight overhead
Exampleconst val STATUS_ACTIVE = "active"enum class Status { ACTIVE, INACTIVE }

✅ Use const val for standalone constants.
✅ Use enum class for predefined sets of values.


Conclusion: When to Use const val?

✅ Use const val when:

  • You need compile-time constants (Strings, Int, Double, etc.).
  • You need constant keys for API requests, Intent extras, or database column names.
  • You want static final behavior without Java’s static final.

❌ Avoid const val when:

  • The value depends on runtime computations.
  • You need objects, lists, or collections.
  • The constant is inside a function or a regular class.


13. What happens if we try to assign a non-constant expression to const val?

Answer:

const val must be assigned only with a compile-time constant. If you try to assign a non-constant expression (like a function call or a variable), you will get a compilation error.

❌ Invalid Code (Runtime Assignment)

kotlin
const val CURRENT_TIME = System.currentTimeMillis() // ❌ ERROR: Must be a constant

✅ Solution (Use val Instead)

kotlin
val currentTime = System.currentTimeMillis() // ✅ Allowed

🚀 Key Takeaway: const val can only be initialized with hardcoded values.


14. Can const val be used inside a data class?

Answer:

No, const val cannot be used inside a data class because data classes are meant for storing runtime values.

❌ Invalid Code

kotlin
data class User(val id: Int, const val name: String) // ❌ ERROR

✅ Solution: Declare constants outside the data class.

kotlin
data class User(val id: Int, val name: String) const val DEFAULT_USER_NAME = "Guest"

🚀 Key Takeaway: const val is not meant for dynamic data storage.


15. What is the difference between const val and buildConfigField in Gradle?

Answer:

Featureconst valbuildConfigField
UsageStatic constants in codeConstants defined at build time
ScopeLimited to Kotlin/Java codeCan be customized per build variant
ModificationHardcoded in codeCan be set in build.gradle

✅ Example of const val:

kotlin
const val API_KEY = "ABC123"

✅ Example of buildConfigField in build.gradle

gradle
android { buildTypes { debug { buildConfigField "String", "API_KEY", "\"DEBUG_KEY\"" } release { buildConfigField "String", "API_KEY", "\"RELEASE_KEY\"" } } }

🚀 Key Takeaway:

  • Use const val for universal static values.
  • Use buildConfigField when values change per build variant.

16. Can const val be used in sealed classes?

Answer:

No, const val cannot be used directly inside a sealed class.

❌ Invalid Code

kotlin
sealed class UserType { const val ADMIN = "Admin" // ❌ ERROR: `const val` not allowed }

✅ Solution: Move const val to a companion object.

kotlin
sealed class UserType { companion object { const val ADMIN = "Admin" } }

🚀 Key Takeaway: const val must be inside a companion object when used in a sealed class.


17. Can const val be used in an Enum?

Answer:

No, const val cannot be used inside an enum class directly.

❌ Invalid Code

kotlin
enum class Status { ACTIVE, INACTIVE; const val MESSAGE = "This is an error" // ❌ ERROR }

✅ Solution: Use a companion object.

kotlin
enum class Status { ACTIVE, INACTIVE; companion object { const val DEFAULT_STATUS = "ACTIVE" } }

🚀 Key Takeaway: Always use a companion object for const val inside an enum class.


18. Can const val be used for localization (strings.xml)?

Answer:

No, const val cannot be used for localized strings because it must be static and known at compile time.

❌ Invalid Code

kotlin
const val WELCOME_MESSAGE = getString(R.string.welcome) // ❌ ERROR

✅ Solution: Store the resource ID instead.

kotlin
const val WELCOME_MESSAGE_ID = R.string.welcome // ✅ Allowed

🚀 Key Takeaway: Use resource IDs, not string values, with const val.


19. How does const val behave with ProGuard?

Answer:

const val values are inlined at compile time, meaning they may be removed during ProGuard's optimization.

✅ Example:

kotlin
const val APP_MODE = "DEBUG"

➡ After ProGuard Optimization (Release Build):

java
System.out.println("DEBUG"); // No variable reference, value is directly inserted

🚀 Key Takeaway: If you change a const val, you must clean and rebuild to avoid stale values in the APK.


20. Real-World Use Cases for const val

Use Case 1: Static Database Column Names

kotlin
object DatabaseConstants { const val TABLE_USERS = "users" const val COLUMN_ID = "id" const val COLUMN_NAME = "name" }

✅ Usage

kotlin
val query = "SELECT * FROM ${DatabaseConstants.TABLE_USERS}"

🚀 Benefit: Avoids hardcoded string mistakes.


Use Case 2: Defining Intent Extra Keys

kotlin
object IntentKeys { const val USER_ID = "extra_user_id" const val USER_NAME = "extra_user_name" }

✅ Usage

kotlin
val intent = Intent(this, ProfileActivity::class.java) intent.putExtra(IntentKeys.USER_ID, 123)

🚀 Benefit: Prevents typos in intent keys.


Use Case 3: Defining SharedPreferences Keys

kotlin
object Preferences { const val PREFS_NAME = "AppPrefs" const val KEY_USER_TOKEN = "user_token" }

✅ Usage

kotlin
val prefs = getSharedPreferences(Preferences.PREFS_NAME, Context.MODE_PRIVATE) prefs.edit().putString(Preferences.KEY_USER_TOKEN, "token123").apply()

🚀 Benefit: Ensures consistent preference keys.


Use Case 4: API Endpoints

kotlin
object ApiEndpoints { const val BASE_URL = "https://api.example.com/" const val LOGIN = "auth/login" const val SIGNUP = "auth/signup" }

✅ Usage

kotlin
val url = "${ApiEndpoints.BASE_URL}${ApiEndpoints.LOGIN}"

🚀 Benefit: Easy API endpoint management.


Summary Table: const val Best Practices

✅ Do This❌ Avoid This
Use const val for static, compile-time constantsDeclaring const val inside classes (Use companion object)
Use const val for database keys, API endpoints, shared preferencesUsing const val for dynamic values (e.g., function calls)
Use const val for intent extras, string keys, configuration valuesUsing const val in sealed class or enum class directly (Use companion object)
Use const val in object or companion object for organizationUsing const val for localized strings (strings.xml)

Conclusion

  • Use const val for:
    ✅ Compile-time constants
    ✅ Static values like API URLs, database column names, shared preferences keys
    ✅ Better code organization and performance optimizations
  • Avoid const val for:
    ❌ Runtime-dependent values
    ❌ Localization strings
    ❌ Values requiring function calls

🔥 Final Thought:
const val is an optimized replacement for static final in Java. Use it for constants that don’t change at runtimeto improve performance and maintainability 

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Kotlin Some important unsorted interview questions and answers

Null safety based Kotlin interview questions and answers