Avatar ·

What is the difference between const and val in Kotlin? Detailed explanation for beginners

Hello everyone! I recently started learning Kotlin and encountered some confusion. In other developers' code, I see two similar keywords: `const` and `val`. At first glance, they do the same thing — declare an immutable variable. But I feel there is some difference between them, otherwise why would both exist?\n\nHere's an example that confuses me:\n\n```kotlin\nval pi = 3.14159\nconst val PI = 3.14159\n```\n\nI understand that both options won't let me change the value after initialization. But why then in one case do I write `const val`, and in the other just `val`? The compiler complains if I try to use `const` inside a function. Why is that?\n\nI also noticed that `const` can only be used with primitive types and strings. And `val` works with any objects. But then why would I need `const` at all?