如何将对象列表作为参数传递给类,Kotlin

6ie5vjzr  于 2023-01-02  发布在  Kotlin
关注(0)|答案(2)|浏览(171)

我如何将一个对象列表作为参数从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) {

}```
bqujaahr

bqujaahr1#

此处构造函数参数中缺少val关键字。
如果要再次重新指定列表,可以将设为var
在Kotlin构造函数中,如果你不定义它,它将是一个特定类的属性。所以它不可能在构造函数之外被访问。

class PayrollSystem(val list: MutableList<Employee>) {

    fun calculatePayroll(){
        //You can access it with list.someThing()
    }
}
rqqzpn5f

rqqzpn5f2#

以防有人会面临类似的任务。

fun main(args: Array<String>) {
    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)
            PayrollSystem(employees).calculatePayroll()
            break;
        }
    }
}

class PayrollSystem(val list: MutableList<SalaryEmployee>) {

    val temp = list
    fun calculatePayroll(){
        temp.forEach{
            println("Employee Payroll\n================")
            println("Payroll for: ${it.id} - ${it.name}\n- Check amount: ${it.monthly_salary}\n")
        }
    }
}

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

    fun calculateSalary(): Int {
        return monthly_salary
    }
}

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

}```

相关问题