Managing Employee Records with Kotlin MutableMap and MutableList

Introducing Methods to Implement

Let's start by discussing the methods we will implement in our EmployeeRecords class.

  • addProject(employeeId: String, projectName: String): Boolean — This method adds a new project to an employee's list of projects. If the project already exists for that employee, the method returns false. Otherwise, it adds the project and returns true.
  • addTask(employeeId: String, projectName: String, task: String): Boolean — This method adds a new task to a specified project for an employee. If the project does not exist for that employee, the method returns false. If the task is added successfully, it returns true.
  • getTasks(employeeId: String, projectName: String): List<String>? — This method retrieves all tasks for a specified project of an employee. If the project does not exist for that employee, the method returns null. Otherwise, it returns the list of tasks.

Step 1: Basic Class Structure

Let's build our EmployeeRecords class step-by-step, ensuring we understand each component clearly.

We'll start with the basic structure of the class and initialize our data storage.

class EmployeeRecords {
    private val records: MutableMap<String, MutableMap<String, MutableList<String>>> = mutableMapOf()
}

fun main() {
    val records = EmployeeRecords()
}

In this initial setup, we define the EmployeeRecords class and create a property records that is a MutableMap. Each key is an employee ID with a corresponding value being another map that holds projects and tasks.

Step 2: Implementing `addProject` Method

Next, we'll implement the addProject method to add projects to an employee's record.

class EmployeeRecords {
    /* Other methods and properties omitted for brevity */

    fun addProject(employeeId: String, projectName: String): Boolean {
        val employeeProjects = records.getOrPut(employeeId) { mutableMapOf() }
        if (projectName in employeeProjects) {
            return false
        } else {
            employeeProjects[projectName] = mutableListOf()
            return true
        }
    }
}

fun main() {
    val records = EmployeeRecords()
    println(records.addProject("E123", "ProjectA"))  // Returns true
    println(records.addProject("E123", "ProjectA"))  // Returns false
}

Here, the addProject method uses getOrPut to check if the given employeeId exists in the records map. This method creates an empty map for an employee if none exists. It checks if the projectName already exists, returning false if it does. Otherwise, it creates a new empty list for tasks and returns true.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal