Library contents

Kotlin List.plus

Build an extended List while retaining the original read-only view of the published route.

A simple example

List.plus

  1. Start with An immutable list containing A
  2. Do this Add B to a new copy
  3. Result New list A, B
Creating a new collection keeps the original list intact.

Syntax

Kotlin syntax
published + stop
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Add a stop to a published bus route

A planner starts with a published route that riders can already see. She needs to add the museum to a draft while keeping the original schedule available to other passengers.

From the programval published = listOf("Station")
Result[Station, Museum]
Lesson.kt
fun main() {
    val published = listOf("Station")
    val draft = published + "Museum"
    println(draft)
}
Output
[Station, Museum]

The draft has two stops while the published route still has just the station.

Advertisements

Extend a draft shortlist

The school office is editing a mutable rehearsal list. Attempt to append one name to the roster. A published read-only list requires a working copy.

GivenEditable list [Ada]
Worked resultName added

Protect a published result

A teacher opens an unmodifiable snapshot of the final roster. Attempt to append one name to the roster. A published read-only list requires a working copy.

GivenUnmodifiable list [Ada]
Worked resultMake a working copy

What to watch for

A Kotlin read-only List interface does not guarantee that some other reference cannot mutate the underlying list.

Documentation for List.plus