Data Filtering and Aggregation in User Management with Kotlin

Introduction

Welcome to today's lesson on applying Kotlin to perform data filtering and aggregation in a real-world scenario using a user management system. We'll start by building a foundational structure that can handle basic user operations. Then, we'll expand it by introducing more advanced functionalities that allow filtering and aggregating user data.

Starter Task Methods

In our starter task, we will implement a class that manages basic operations on a collection of user data, specifically handling the addition of new users, retrieving user profiles, and updating user profiles.

Here are the starter task methods:

  • addUser(userId: String, age: Int, country: String, subscribed: Boolean): Boolean - adds a new user with the specified attributes. Returns true if the user was added successfully and false if a user with the same userId already exists.

  • getUser(userId: String): Map<String, Any?>? - returns the user's profile as a map if the user exists; otherwise, returns null.

  • updateUser(userId: String, age: Int?, country: String?, subscribed: Boolean?): Boolean - updates the user's profile based on non-null parameters. Returns true if the user exists and was updated, false otherwise.

Solution for the Starter Task

Here is the implementation of our starter task using Kotlin:

class UserManager {
    private val users = mutableMapOf<String, MutableMap<String, Any?>>()

    fun addUser(userId: String, age: Int, country: String, subscribed: Boolean): Boolean {
        if (users.containsKey(userId)) {
            return false
        }
        users[userId] = mutableMapOf("age" to age, "country" to country, "subscribed" to subscribed)
        return true
    }

    fun getUser(userId: String): Map<String, Any?>? {
        return users[userId]
    }

    fun updateUser(userId: String, age: Int?, country: String?, subscribed: Boolean?): Boolean {
        val user = users[userId] ?: return false
        age?.let { user["age"] = it }
        country?.let { user["country"] = it }
        subscribed?.let { user["subscribed"] = it }
        return true
    }
}

// Example usage
fun main() {
    val um = UserManager()
    println(um.addUser("u1", 25, "USA", true))  // true
    println(um.addUser("u2", 30, "Canada", false))  // true
    println(um.addUser("u1", 22, "Mexico", true))  // false
    println(um.getUser("u1"))  // {age=25, country=USA, subscribed=true}
    println(um.updateUser("u1", 26, null, null))  // true
    println(um.updateUser("u3", 19, "UK", false))  // false
}

This implementation covers all our starter methods. Let's move forward and introduce more complex functionalities.

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