[Kotlin] mutableList with toList

List is not mutable, when you want to add data into list, you can do is:

"adding data to a mutableList", then return a immutable list by calling toList() function

 private val hiddenSeats = mutableListOf<Seat>()
 val seats
 get() = hiddenSeats.toList()

Example Code:

import java.math.BigDecimal

data class Seat(val row: Int, val num: Int, val price: BigDecimal, val description: String) {
    override fun toString(): String = "Seat $row-$num $price ($description)"
}

class Theater {
    private val hiddenSeats = mutableListOf<Seat>()

    constructor() {

        fun getPrice(row: Int, num: Int): BigDecimal {
            return when {
                row >=14 -> BigDecimal(14.50)
                num <=3 || num >= 34 -> BigDecimal(16.50)
                row == 1 -> BigDecimal(21)
                else -> BigDecimal(18)
            }
        }

        fun getDescription(row: Int, num: Int): String {
            return when {
                row == 15 -> "Back row"
                row == 14 -> "Cheaper seat"
                num < 3 || num >=34 -> "Restricted view"
                row <= 2 -> "Best view"
                else -> "Standard view"
            }
        }

        for (row in 1..15) {
            for (num in  1..36) {
                hiddenSeats.add(Seat(row, num, getPrice(row, num), getDescription(row, num)))
            }
        }
    }

    val seats
    get() = hiddenSeats.toList()
}

fun main(args: Array<String>) {
    val cheapSeats = Theater().seats.filter {it.price == BigDecimal(14.50)}
    for (seat in cheapSeats) println(seat)
}
原文地址:https://www.cnblogs.com/Answer1215/p/13900094.html