0
0
Kotlinprogramming~3 mins

Why String type and immutability in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if changing a word in your story accidentally erased the whole page?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
var name = "Alice"
// name[0] = 'E'  // Not allowed, strings are immutable
After
var name = "Alice"
name = "E" + name.substring(1)  // Creates a new string safely
What It Enables

This lets you work with text confidently, knowing your original data won't change unexpectedly, making your programs easier to understand and debug.

Real Life Example

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.

Key Takeaways

Strings in Kotlin cannot be changed after creation.

Modifying strings creates new copies, protecting original data.

This makes programs safer and easier to maintain.