What is the difference between const and val in Kotlin? When to use which?
Hello! I started learning Kotlin and can't understand the difference between `const` and `val`. They both seem to declare immutable values, but the compiler complains when I try to use `const` inside a function or with some expressions.
Here's an example that confuses me:
```kotlin
// This works
val name = "John"
val currentTime = System.currentTimeMillis()
// But this doesn't work - compilation error
const val name2 = "John"
const val currentTime2 = System.currentTimeMillis() // Error!
```
Why doesn't `const val currentTime2` compile? After all, `val` is also immutable. Also I noticed that `const` can only be used at the file level or inside an `object`, while `val` can be used anywhere. What is the deep difference here? When should I use `const` and when just `val`?
Explain please.
No answers yet.
Log in to leave an answer
Blogs