Search code examples
listkotlinobjectparameters

How to pass a list of objects as a parameter to a class. Kotlin


How can I pass a list of objecs from main to a class, as parameter?

I need to pass a list of employees to PayrollSystem class as a parameter.

Could someone help, please?

    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) {

}``` 

Solution

  • Here you are missing val keyword in constructor params.

    You can make as var if you are reassigning the list again.

    In kotlin constructor, if you don't define it would be a property of the particular class. So its not possible to access outside constructor.

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