What if changing a word in your story accidentally erased the whole page?
Why String type and immutability in Kotlin? - Purpose & Use Cases
Imagine you have a long list of names written on paper. Every time you want to change a name, you erase it and write a new one. This takes time and can cause mistakes if you erase the wrong part.
Manually changing strings by rewriting them is slow and risky. If you try to change a string directly, you might accidentally lose data or create bugs because strings are often shared in many places.
Kotlin's String type is immutable, meaning once you create a string, it cannot be changed. Instead, when you modify a string, Kotlin creates a new one. This keeps your data safe and your program more reliable.
var name = "Alice" // name[0] = 'E' // Not allowed, strings are immutable
var name = "Alice" name = "E" + name.substring(1) // Creates a new string safely
This lets you work with text confidently, knowing your original data won't change unexpectedly, making your programs easier to understand and debug.
When building a chat app, each message text is a string. Immutability ensures that once a message is sent, it cannot be changed accidentally, preserving the chat history accurately.
Strings in Kotlin cannot be changed after creation.
Modifying strings creates new copies, protecting original data.
This makes programs safer and easier to maintain.