Kotlin中如何将对象列表作为参数传入类?以员工列表传PayrollSystem为例
在Kotlin中向PayrollSystem类传递员工列表的实现方案
核心修改点
- 修正
PayrollSystem类的泛型参数:将小写的employee改为大写的Employee(匹配父类类名) - 优化员工列表初始化:直接创建空的可变列表,避免后续删除占位元素的冗余操作
- 在main函数中完成员工信息收集后,实例化
PayrollSystem并传入员工列表 - 完善
calculatePayroll方法,实现薪资清单的打印逻辑 - 简化
SalaryEmployee类的属性声明,无需重复override父类属性
完整修正代码
fun main() { var index = 0 val employees = mutableListOf<Employee>() // 直接初始化空列表 val quitInput = "0" while (true) { print("请输入员工姓名(输入0退出):") val input = readLine() ?: break // 处理输入为空的情况 if (input != quitInput) { index++ print("请输入月薪:") val wage = readLine()?.toIntOrNull() ?: run { println("输入的薪资无效,请重新操作") continue } employees.add(SalaryEmployee(index, input, wage)) } else { // 创建PayrollSystem实例并传入员工列表 val payrollSystem = PayrollSystem(employees) payrollSystem.calculatePayroll() break } } } class PayrollSystem(private val employeeList: List<Employee>) { fun calculatePayroll() { println("=== 员工薪资清单 ===") employeeList.forEach { employee -> if (employee is SalaryEmployee) { println("ID: ${employee.id} 姓名: ${employee.name} 月薪: ${employee.monthly_salary}") } } } } open class Employee(open val id: Int, open val name: String) class SalaryEmployee( override val id: Int, override val name: String, val monthly_salary: Int ) : Employee(id, name)
代码说明
- 列表初始化优化:去掉原代码中占位的无效员工对象,直接创建空的
MutableList<Employee>,省去后续删除占位元素的操作 - 输入安全处理:对
readLine()的返回值做空值判断,用toIntOrNull()避免输入非数字时抛出异常,提升程序稳定性 - 列表传递实现:在用户输入0退出时,将收集完成的员工列表作为参数传入
PayrollSystem的构造函数,完成对象列表的传递 - 薪资逻辑实现:在
calculatePayroll中通过类型判断employee is SalaryEmployee,安全访问子类的薪资属性并打印完整清单 - 子类属性简化:
SalaryEmployee的主构造函数直接用override修饰继承自父类的id和name,无需重复声明属性
内容的提问来源于stack exchange,提问作者Elissei Hilakivi
相关产品推荐
相关产品推荐

