Building a Sample Project in Kotlin

In this article, we’re diving directly into building a complete sample project using Kotlin! Let’s put together a simple task management application that allows users to add, view, and remove tasks. We’ll cover various aspects of Kotlin programming, including data classes, collections, functions, and how to work with user input. This guide will provide a hands-on experience to solidify your understanding of Kotlin concepts.

Step 1: Setting Up Your Kotlin Environment

Before we start coding, ensure you have your Kotlin environment set up. You can either use an Integrated Development Environment (IDE) like IntelliJ IDEA or an online compiler like Kotlin Playground.

  1. Install IntelliJ IDEA:

    • Download it from the JetBrains website.
    • Open IntelliJ IDEA and create a new Kotlin project.
  2. Create a file for your main code:

    • Inside your project, create a new Kotlin file named TaskManager.kt.

Step 2: Define Our Task Data Class

In Kotlin, data classes are used to hold data. Tasks in our app will have a title and a completion status. Here’s how to define the Task data class:

data class Task(val title: String, var isCompleted: Boolean = false)

In this line, we create a Task class with two properties: title (of type String) and isCompleted (a Boolean which defaults to false).

Step 3: Setting Up the TaskManager Class

Next, we’ll create a TaskManager class that will handle our tasks. This class will allow for adding, viewing, and completing or removing tasks. Here’s how to set it up:

class TaskManager {
    private val tasks = mutableListOf<Task>()

    fun addTask(task: Task) {
        tasks.add(task)
        println("Task added: ${task.title}")
    }

    fun viewTasks() {
        if (tasks.isEmpty()) {
            println("No tasks available.")
        } else {
            println("Current Tasks:")
            tasks.forEachIndexed { index, task ->
                val status = if (task.isCompleted) "✓" else "✗"
                println("${index + 1}. [$status] ${task.title}")
            }
        }
    }

    fun completeTask(index: Int) {
        if (index >= 0 && index < tasks.size) {
            tasks[index].isCompleted = true
            println("Task marked as complete: ${tasks[index].title}")
        } else {
            println("Invalid task index.")
        }
    }

    fun removeTask(index: Int) {
        if (index >= 0 && index < tasks.size) {
            println("Task removed: ${tasks[index].title}")
            tasks.removeAt(index)
        } else {
            println("Invalid task index.")
        }
    }
}

Explanation:

  • Task List: We have a mutable list of tasks that can be modified (add, remove, etc.).
  • addTask(): Adds a new task to the list and prints feedback.
  • viewTasks(): Displays the current tasks along with their completion statuses.
  • completeTask(): Marks a task as completed based on its index.
  • removeTask(): Removes a task based on its index.

Step 4: Creating the User Interface

Now that we have our TaskManager, let’s create a simple text-based user interface (UI) to interact with it. Here’s how you can implement a basic console interface:

fun main() {
    val taskManager = TaskManager()
    while (true) {
        println("\n---- Task Manager ----")
        println("1. Add Task")
        println("2. View Tasks")
        println("3. Complete Task")
        println("4. Remove Task")
        println("5. Exit")
        print("Choose an option: ")

        when (readLine()?.toIntOrNull()) {
            1 -> {
                print("Enter task title: ")
                val title = readLine().orEmpty()
                taskManager.addTask(Task(title))
            }
            2 -> taskManager.viewTasks()
            3 -> {
                print("Enter task index to complete: ")
                val index = readLine()?.toIntOrNull()?.minus(1)
                if (index != null) {
                    taskManager.completeTask(index)
                } else {
                    println("Invalid input.")
                }
            }
            4 -> {
                print("Enter task index to remove: ")
                val index = readLine()?.toIntOrNull()?.minus(1)
                if (index != null) {
                    taskManager.removeTask(index)
                } else {
                    println("Invalid input.")
                }
            }
            5 -> {
                println("Exiting Task Manager.")
                return
            }
            else -> println("Invalid option. Please try again.")
        }
    }
}

Explanation:

  • Menu Loop: The main function provides a simple textual menu for the user to choose from.
  • Input Reading: It uses readLine() to capture user input and processes it accordingly.
  • User Feedback: Each action gives feedback to the user to confirm that the action was completed.

Step 5: Running the Application

You can run the application by clicking the Run button or executing the program from the terminal if you’re working with command-line tools.

As you interact with your task manager, ensure that each feature works correctly—adding, viewing, completing, and removing tasks as intended.

Step 6: Enhancements and Further Learning

Now that you have a basic task manager, there are many potential enhancements you could make:

  1. Data Persistence: Implement functionality to save tasks to a file so that they persist even after the program exits. You can utilize Kotlin's file handling capabilities for this.
  2. Priority Levels: Add priority levels to tasks by enhancing the Task data class.
  3. Task Sorting: Implement functionality to sort tasks based on their status or title.
  4. Graphical User Interface (GUI): Once comfortable with the basics of Kotlin, consider exploring frameworks like TornadoFX for building desktop applications with a GUI.

Conclusion

Congratulations! You’ve successfully built a task management application in Kotlin from scratch. This project allowed you to apply your understanding of core Kotlin concepts and served as a stepping stone toward more complex projects. Keep experimenting with your application and explore additional features to continue learning and improving your Kotlin skills. Happy coding!