0
0
Kotlinprogramming~30 mins

Mutable vs immutable interfaces in Kotlin - Hands-On Comparison

Choose your learning style9 modes available
Mutable vs Immutable Interfaces in Kotlin
📖 Scenario: Imagine you are building a simple contact list app. You want to keep a list of contacts where some parts of your program can only read the contacts, while other parts can add or remove contacts.
🎯 Goal: You will create a Kotlin program that shows the difference between mutable and immutable interfaces by using List and MutableList. You will start by creating a list of contacts, then add a helper variable, use the mutable interface to add a contact, and finally print the updated list.
📋 What You'll Learn
Create an immutable list of contacts using List
Create a mutable list variable from the immutable list
Add a new contact to the mutable list
Print the final list of contacts
💡 Why This Matters
🌍 Real World
Many apps need to protect data from accidental changes by using immutable interfaces, while allowing controlled changes with mutable interfaces.
💼 Career
Understanding mutable vs immutable collections is important for writing safe and clear Kotlin code in Android development and backend services.
Progress0 / 4 steps
1
Create an immutable list of contacts
Create a variable called contacts that holds an immutable list of strings with these exact values: "Alice", "Bob", "Charlie" using listOf().
Kotlin
Need a hint?

Use val contacts: List = listOf("Alice", "Bob", "Charlie") to create an immutable list.

2
Create a mutable list from the immutable list
Create a variable called mutableContacts that holds a mutable list of strings by copying the contacts list using toMutableList().
Kotlin
Need a hint?

Use toMutableList() on contacts to create a mutable copy.

3
Add a new contact to the mutable list
Add the string "Diana" to the mutableContacts list using the add() method.
Kotlin
Need a hint?

Use mutableContacts.add("Diana") to add the new contact.

4
Print the updated list of contacts
Print the mutableContacts list using println() to show all contacts including the new one.
Kotlin
Need a hint?

Use println(mutableContacts) to display the list.