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:
✅ Key Points:
const valcan only be used inside top-level declarations or insideobjectorcompanion object.- The value must be known at compile time.
2. What is the difference between const val and val in Kotlin?
| Feature | const val | val |
|---|---|---|
| Mutability | Immutable (cannot change) | Immutable (but can be assigned dynamically) |
| Initialization | Must be initialized with a compile-time constant | Can be initialized with a runtime value |
| Usage | Only in top-level, object, or companion object | Can be used anywhere (class, function, etc.) |
| Example | const val MAX = 10 | val max = getMaxValue() |
Example:
✅ Key Takeaway:
const valis resolved at compile time.valcan be assigned at runtime.
3. Where can const val be used in Kotlin?
Answer:
- Top-level in a Kotlin file ✅
- Inside
objectorcompanion object✅ - Inside a regular class (as a member variable) ❌ (Not allowed!)
Example:
4. Can const be used with non-primitive types?
Answer:
No. const val only supports primitive types like String, Int, Double, Boolean, Long, Float, and Char.
✅ Allowed:
❌ Not Allowed:
✅ Key Takeaway:
constcannot be used with collections, objects, or functions.
Intermediate Level
5. What is the difference between const val and companion object?
Answer:
| Feature | const val | companion object |
|---|---|---|
| Access | Directly accessible | Needs class reference |
| Usage | Compile-time constants only | Can hold runtime logic |
| Example | const val MAX = 10 | companion object { val max = getMaxValue() } |
Example:
✅ Key Takeaway:
- Use
const valfor static constants. - Use
companion objectfor 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:
✅ Solution: Declare const val at the top-level or inside an object.
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:
✅ Key Takeaway:
const valcan be inside aninterfaceusing 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:
➡ Decompiled Java Code:
✅ Key Takeaway:
const valbehaves like a public static final field in Java.
9. What is the difference between const val and static final in Java?
| Feature | const val (Kotlin) | static final (Java) |
|---|---|---|
| Access | Directly accessible | Needs ClassName.FIELD |
| Type | val only | Can be any type |
| Initialization | Compile-time only | Can be set in static block |
✅ Kotlin
✅ Equivalent Java
✅ Key Takeaway:
- Kotlin
const valis a direct replacement forstatic finalin Java.
10. Real-World Example: Using const val for API Configuration
Scenario: You need static API keys for network requests.
✅ Usage:
🚀 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.
✅ Usage:
🚀 Benefit: Prevents hardcoded strings and typos!
12. When should you use const val vs enum class?
| Feature | const val | enum class |
|---|---|---|
| Usage | Simple constants | Group of related values |
| Performance | Faster, no object creation | Slight overhead |
| Example | const 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:
A 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)
✅ Solution (Use val Instead)
🚀 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
✅ Solution: Declare constants outside the data class.
🚀 Key Takeaway: const val is not meant for dynamic data storage.
15. What is the difference between const val and buildConfigField in Gradle?
Answer:
| Feature | const val | buildConfigField |
|---|---|---|
| Usage | Static constants in code | Constants defined at build time |
| Scope | Limited to Kotlin/Java code | Can be customized per build variant |
| Modification | Hardcoded in code | Can be set in build.gradle |
✅ Example of const val:
✅ Example of buildConfigField in build.gradle
🚀 Key Takeaway:
- Use
const valfor universal static values. - Use
buildConfigFieldwhen 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
✅ Solution: Move const val to a companion object.
🚀 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
✅ Solution: Use a companion object.
🚀 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
✅ Solution: Store the resource ID instead.
🚀 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:
➡ After ProGuard Optimization (Release Build):
🚀 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
✅ Usage
🚀 Benefit: Avoids hardcoded string mistakes.
Use Case 2: Defining Intent Extra Keys
✅ Usage
🚀 Benefit: Prevents typos in intent keys.
Use Case 3: Defining SharedPreferences Keys
✅ Usage
🚀 Benefit: Ensures consistent preference keys.
Use Case 4: API Endpoints
✅ Usage
🚀 Benefit: Easy API endpoint management.
Summary Table: const val Best Practices
| ✅ Do This | ❌ Avoid This |
|---|---|
Use const val for static, compile-time constants | Declaring const val inside classes (Use companion object) |
Use const val for database keys, API endpoints, shared preferences | Using const val for dynamic values (e.g., function calls) |
Use const val for intent extras, string keys, configuration values | Using const val in sealed class or enum class directly (Use companion object) |
Use const val in object or companion object for organization | Using const val for localized strings (strings.xml) |
Conclusion
- Use
const valfor:
✅ Compile-time constants
✅ Static values like API URLs, database column names, shared preferences keys
✅ Better code organization and performance optimizations - Avoid
const valfor:
❌ 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
Post a Comment