What is the advantage of using const in Kotlin? (const val vs val)
Tier: EssentialDifficulty: EasyAsked at: meesho
const val gets inlined by the compiler at compile time, so there's no runtime lookup cost, while a plain val in an object is a real property that gets read through a getter call every time you use it.
object Constants {
const val BASE_URL = "https://api.example.com"
val cachedValue = "computed"
}
If you decompile the bytecode, every place that references BASE_URL has the literal string "https://api.example.com" baked directly into it. There's no Constants object being touched at all at that call site. A reference to cachedValue, on the other hand, compiles down to Constants.INSTANCE.getCachedValue(), an actual method call on a singleton instance, every single time.
The tradeoff is that const val only works for compile time constants. That means primitive types and String, declared at the top level or inside an object, never inside a class instance or computed from a function call. val can hold anything, including a value computed at runtime. So the rule of thumb is this. Use const val for true fixed constants like API base URLs or keys, and reach for regular val when the value isn't known until runtime.