zoukankan      html  css  js  c++  java
  • [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)
    }
  • 相关阅读:
    webOFBiz10.4
    堆栈知识
    eas bos二次开发总结[第三方jar、jcom、二次开发包放置]
    计算机编程英语词汇(三)
    计算机英语(四)
    KDTable 表达式应用工具类
    Verilog 流水线加法器
    datagridview 积累
    ajax 调用 webserver
    windows7 vs2008问题结合
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13900094.html
Copyright © 2011-2022 走看看