Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created July 5, 2025 21:14
Show Gist options
  • Save gbajaj/ca8bc3f4ee2ecf14b40809792f676eec to your computer and use it in GitHub Desktop.
Save gbajaj/ca8bc3f4ee2ecf14b40809792f676eec to your computer and use it in GitHub Desktop.
Snippet that defines an empty mutable 2D list, adds values to it, and then converts it into a fully immutable 2D list.
fun main() {
// 1. Define an empty mutable 2D list
val twoDList = mutableListOf<MutableList<Int>>()
println("1. Initial empty mutable list: $twoDList")
// 2. Add inner lists to it later
twoDList.add(mutableListOf(10, 20, 30))
twoDList.add(mutableListOf(40, 50, 60))
println("2. Mutable list after adding rows: $twoDList")
// You can still modify it
twoDList[0].add(99)
println("3. After modifying an inner list: $twoDList")
// 4. Convert the final structure to an immutable 2D list
val immutable2DList: List<List<Int>> = twoDList.map { it.toList() }
println("4. Final immutable list: $immutable2DList")
// Any attempt to modify immutable2DList will now result in a compile error.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment