【问题标题】:How to pass a list of objects as a parameter to a class. Kotlin如何将对象列表作为参数传递给类。科特林
【发布时间】:2022-12-31 03:16:56
【问题描述】:

如何将对象列表作为参数从 main 传递给类?

我需要将员工列表作为参数传递给 PayrollSystem 类。

有人可以帮忙吗?

    var index = 0
    val employees = mutableListOf(SalaryEmployee(index, "blablabla", 0))
    val x: String = "0"
    while(true) {
        print("Please enter employee name (0 to quit):")
        var input = readLine()!!.toString()
        if (input != x) {
            index++
            print("Please enter salary:")
            var wage = readLine()!!.toInt()
            employees.add(SalaryEmployee(index, input, wage))
        }
        else {
            employees.removeAt(0)
            employees.forEach {
                SalaryEmployee(it.id, it.name, it.monthly_salary).print()
            }
            break;
        }
    }
}

class PayrollSystem(list: MutableList<employee>) {

    val temp = list
    fun calculatePayroll(){

    }
}

class SalaryEmployee(id: Int, name: String, val monthly_salary: Int) : Employee(id, name){
    override val id = id
    override val name = name
    fun print() {
        println("Id: $id Name: $name Salary: $monthly_salary")
    }
}

open class Employee(open val id: Int, open val name: String) {

}``` 

【问题讨论】:

    标签: list kotlin object parameters


    【解决方案1】:

    在这里,您在构造函数参数中缺少 val 关键字。

    如果您要再次重新分配列表,您可以将其设为var

    在 kotlin 构造函数中,如果您不定义它将是特定类的属性。所以它不可能访问外部构造函数。

    class PayrollSystem(val list: MutableList<Employee>) {
    
        fun calculatePayroll(){
            //You can access it with list.someThing()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-30
      • 2023-03-04
      • 2021-12-31
      • 2019-07-23
      • 1970-01-01
      • 2021-11-03
      • 2019-03-02
      • 1970-01-01
      • 2012-09-16
      相关资源
      最近更新 更多