We use mutable and immutable interfaces to control if data can be changed or not. This helps keep our programs safe and clear.
0
0
Mutable vs immutable interfaces in Kotlin
Introduction
When you want to share data but prevent others from changing it.
When you need to update data safely in one place.
When you want to avoid accidental changes to important information.
When designing APIs to clearly show which parts can be changed.
When working with collections where some should stay fixed and others can change.
Syntax
Kotlin
interface ReadOnlyList<T> { fun get(index: Int): T val size: Int } interface MutableList<T> : ReadOnlyList<T> { fun add(item: T) fun removeAt(index: Int) }
Immutable interfaces only allow reading data, no changes.
Mutable interfaces extend immutable ones and add methods to change data.
Examples
This interface allows only reading items and size, no changes.
Kotlin
interface ReadOnlyList<T> { fun get(index: Int): T val size: Int }
This interface allows adding and removing items, so it is mutable.
Kotlin
interface MutableList<T> : ReadOnlyList<T> { fun add(item: T) fun removeAt(index: Int) }
You can use a read-only interface to prevent changes.
Kotlin
val readOnly: ReadOnlyList<String> = ... // readOnly.get(0) works // readOnly.add("new") does NOT work
Mutable interface lets you read and change the list.
Kotlin
val mutable: MutableList<String> = ... mutable.add("new") // works mutable.get(0) // works
Sample Program
This program shows a mutable list that you can add to and remove from. It prints the size and first item before and after removal.
Kotlin
interface ReadOnlyList<T> { fun get(index: Int): T val size: Int } interface MutableList<T> : ReadOnlyList<T> { fun add(item: T) fun removeAt(index: Int) } class SimpleList<T> : MutableList<T> { private val items = mutableListOf<T>() override fun get(index: Int) = items[index] override val size get() = items.size override fun add(item: T) { items.add(item) } override fun removeAt(index: Int) { items.removeAt(index) } } fun main() { val list: MutableList<String> = SimpleList() list.add("apple") list.add("banana") println("Size: ${list.size}") println("First item: ${list.get(0)}") list.removeAt(0) println("Size after removal: ${list.size}") println("First item now: ${list.get(0)}") }
OutputSuccess
Important Notes
Immutable interfaces help avoid bugs by preventing unwanted changes.
Mutable interfaces should be used carefully to keep data consistent.
In Kotlin, many standard collections have both mutable and read-only versions.
Summary
Immutable interfaces allow only reading data.
Mutable interfaces allow changing data and usually extend immutable ones.
Use immutable interfaces to protect data and mutable ones when changes are needed.