• [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)
    }
  • 相关阅读:
    Eletron 打开文件夹,截图
    nodejs 与 json
    drupal sql 源码解析query.inc 文件
    The maximum column size is 767 bytes (Mysql)
    php 过滤emoji
    Mysql delete操作
    Mysql update 一个表中自己的数据
    form 表单排序
    jquery parents用法
    MYSQL数据库重点:流程控制语句
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13900094.html
Copyright © 2020-2023  润新知