CodeGym /Courses /Kotlin SELF /Practical example: parsing input and updating collections...

Practical example: parsing input and updating collections

Kotlin SELF
Level 20, Lesson 4
Available

1. Why command logic is needed in a console app

A console program without commands is like a coffee shop without a menu: the coffee might exist somewhere, but it’s unclear how to order it. Command logic is needed so the user can control the application’s state with short, clear phrases: add ..., list, remove .... This turns a set of disconnected functions into a single flow: read a line → understand the intent → modify the collection → show the result.

Let’s imagine we’re writing a mini app called TaskBox — a task list in the console. This is not a “real” space-station-level TODO list, but a learning version: add a task, show the list, remove a task. What matters is not a rich feature set, but the architecture: the code should be readable and should not break collections during iteration.

The application state will be simple:

  • MutableList<String> — a list of tasks (each task is just a string).
  • a command-reading loop — the user enters lines until they type exit.

Command and argument

Almost all console utilities follow the principle: there is a command (what to do) and sometimes there is an argument (what to do it with). We don’t need complex syntax with quotes and escaping (that’s a special kind of pain), so we’ll use a practical learning format: the command is the first word, and the argument is everything after the first space. That’s enough to build a robust flow without unnecessary magic.

Here’s what it looks like for TaskBox:

Command Input example Meaning
add
add buy milk
add a task
list
list
print all tasks
remove
remove 2
remove a task by number (human-friendly)
remove
remove buy milk
remove a task by exact text (if it doesn’t look like a number)
help
help
show help
exit
exit
exit the program

Key agreement: the user-facing number starts at 1, while the list index starts at 0. This is that “timeless classic” because of which programmers sometimes talk to people with a slight sadness in their eyes.

2. Normalization and parsing of input

Line normalization

Before parsing a command, it’s useful to make the line a bit neater: remove leading/trailing spaces and unify the command’s letter case. This is not decoration — it’s protection against input like " LIST " or "Add buy milk". The user doesn’t have to remember our ideal format; our job is to make the program patient (within reason).

The rule will be: convert the command to lowercase; keep the argument as-is (except for trim()), because task text may use any casing, and we don’t want to suddenly turn “Buy Milk” into “buy milk”.

Mini example of normalization:

fun normalizeInput(line: String): String {
    return line.trim()
}

fun main() {
    val raw = "   Add   buy milk   "
    val normalized = normalizeInput(raw)
    println(normalized) // Add   buy milk
}

Note: we do not “collapse” multiple spaces inside the string. We don’t need that yet. For a learning parser, it’s enough to split the line by the first space, and then treat the argument “as-is”.

Parsing the command

Now we’ll make a function that accepts a string and returns Pair<String, String?>: first is the command, second is the argument or null if there isn’t one. This is exactly the moment when Pair becomes a convenient “envelope” for two values, without inventing our own types (custom classes come later in the course).

It’s important to handle three cases: an empty string (after trim()), a string without spaces (command only), and a string with a command and an argument.

fun parseCommand(line: String): Pair<String, String?> {
    val s = line.trim()
    if (s.isEmpty()) return "" to null

    val spaceIndex = s.indexOf(' ')
    return if (spaceIndex == -1) {
        s.lowercase() to null
    } else {
        val cmd = s.substring(0, spaceIndex).lowercase()
        val arg = s.substring(spaceIndex + 1).trim()
        cmd to arg
    }
}

There’s an important detail here: substring(spaceIndex + 1) takes “everything after the space”. If the user typed add buy milk, then arg will start with spaces, so we call trim() again to get clean text.

Let’s test with a few inputs:

fun main() {
    println(parseCommand("list"))                 // (list, null)
    println(parseCommand(" add   milk  "))        // (add, milk)
    println(parseCommand("   "))                  // (, null)
}

The printed Pair format looks like (first, second). That’s fine: that’s how Kotlin shows pairs in toString().

3. Command dispatch via when

Once the command is recognized, we need to decide what to do. For that, when is ideal: it reads like a routing table — “if the command is this, do that.” It’s important to keep branches short and clear: a command should do one thing and not try to “reinvent the entire world” along the way.

Let’s agree on TaskBox architecture up front:

  • main() — only the read loop and function calls.
  • parseCommand() — parsing only.
  • handleCommand() — a dispatcher that invokes concrete operations.
  • operations (addTask, printTasks, removeTask) — separate functions, so we don’t bloat the when.

Let’s start with the base: the command handler function returns a Boolean: true means continue the loop; false means exit.

fun handleCommand(cmd: String, arg: String?, tasks: MutableList<String>): Boolean {
    return when (cmd) {
        "add" -> { addTask(tasks, arg); true }
        "list" -> { printTasks(tasks); true }
        "remove" -> { removeTask(tasks, arg); true }
        "help" -> { printHelp(); true }
        "exit" -> false
        "" -> true
        else -> { println("Unknown command: $cmd"); true }
    }
}

Note the "" branch: this is the case when the user entered an empty line or just spaces. We simply do nothing and continue.

4. The add and list commands

The add command

Adding an element is the simplest list mutation: we take a string and put it into tasks. In Kotlin, mutable collections have an add() method that appends an element to the end. But in a console UI, the main challenge is not add(); it’s that the user can forget the argument or enter an empty string.

Let’s make a neat function: if there is no argument or it’s empty, print a hint and change nothing.

fun addTask(tasks: MutableList<String>, text: String?) {
    val task = text?.trim()
    if (task.isNullOrEmpty()) {
        println("Format: add <task text>")
        return
    }

    tasks.add(task)
    println("Added: $task") // Added: buy milk
}

Here isNullOrEmpty() is a convenient way to say “either null or an empty string.” We could do two checks manually, but let Kotlin do a bit of work for us.

The list command

Printing the list is a read-only operation. And here it’s easy to write either clear code or “I’m a programmer, I see it this way.” We need to print tasks with numbers starting at 1, because that’s what users are used to: item 1, item 2, item 3.

Technically, you can number in different ways: via indices or withIndex(). For this command, withIndex() is more logical because we want both the index and the value at once. In previous lectures, we discussed that list indexes start at 0 and go up to lastIndex, i.e., up to size - 1.

fun printTasks(tasks: List<String>) {
    if (tasks.isEmpty()) {
        println("The task list is empty.") // The task list is empty.
        return
    }

    for ((i, task) in tasks.withIndex()) {
        println("${i + 1}. $task")
    }
}

Notice: the parameter is List<String>, not MutableList<String>. That’s good style: a “print” function doesn’t have to be able to mutate the list, so we make the contract stricter — read-only.

5. The remove command and safe deletion

Remove by number or by text

Removal is the most nerve-wracking operation. Not because remove is hard, but because it often leads to “I’ll just remove it right during iteration,” and then the adventures begin. We already know safe removal strategies, but for the remove command we usually just need to remove one element.

There are two convenient semantics:

  • if the argument is a number, treat it as the task number (starting from 1), convert it to an index (minus 1), check bounds, and call removeAt(index);
  • if the argument is not a number, remove by value via remove(value).

An important detail about remove(value): it removes one occurrence and returns a Boolean indicating whether removal happened.

Let’s implement it neatly:

fun removeTask(tasks: MutableList<String>, arg: String?) {
    val s = arg?.trim()
    if (s.isNullOrEmpty()) {
        println("Format: remove <number|text>")
        return
    }

    val number = s.toIntOrNull()
    if (number != null) {
        removeByNumber(tasks, number)
    } else {
        removeByText(tasks, s)
    }
}

Now the “by number” specifics:

fun removeByNumber(tasks: MutableList<String>, number: Int) {
    val index = number - 1
    if (index !in tasks.indices) {
        println("No task with number $number")
        return
    }

    val removed = tasks.removeAt(index)
    println("Removed: $removed") // Removed: buy milk
}

Here tasks.indices is the most reliable way to check bounds: it’s the range of valid indices. It is automatically correct for any list size and saves you from the classic “mixed up size and last index” mistake. The index principle (0…lastIndex) is the basic list model in Kotlin.

And removal “by text”:

fun removeByText(tasks: MutableList<String>, text: String) {
    val ok = tasks.remove(text)
    if (ok) {
        println("Removed: $text") // Removed: buy milk
    } else {
        println("Task not found: $text")
    }
}

Note: “remove by text” removes the first match. If there are multiple identical tasks, this behavior is usually fine for a simple learning app.

Bulk removal via iterator

Sometimes you don’t want “remove one element,” but “remove all tasks equal to X” or “remove all empty/invalid tasks.” This is where people step on rakes: they write for (x in tasks) tasks.remove(x) and get either skipped elements or an exception.

Today we’re not building a rich purge command, but we’ll write a useful helper function removeAllEquals. It will serve as an example of “correct removal during traversal” — via an iterator. This is exactly the technique we prepared in the lecture on safe deletion.

fun removeAllEquals(tasks: MutableList<String>, target: String) {
    val it = tasks.iterator()
    while (it.hasNext()) {
        val task = it.next()
        if (task == target) {
            it.remove()
        }
    }
}

Why is this important even in a “simple” TaskBox? Because as soon as you expand functionality (for example, add a command “remove everything that contains the word spam”), you end up in a bulk-removal situation. And there you can’t “hope for the best” — you must choose a correct traversal/removal strategy.

6. Assembling the app: main, help, and the command loop

Now let’s assemble everything into a single flow. It’s important to keep main() as the “conductor”: it should not parse, validate, and remove by itself. Its job is to read lines, call parseCommand, pass the result into handleCommand, and decide whether to continue the loop.

A small flowchart of the process:

flowchart TD
    A["readln()"] --> B[trim + parseCommand]
    B --> C[cmd + arg]
    C --> D["when(cmd)"]
    D --> E[add/list/remove/help]
    E --> F[updated tasks and/or printed result]
    F --> A
    D --> G[exit]

And now the main() code (still short and readable):

fun main() {
    val tasks = mutableListOf<String>()
    println("TaskBox. Type help for assistance.")

    while (true) {
        print("> ")
        val (cmd, arg) = parseCommand(readln())

        val shouldContinue = handleCommand(cmd, arg, tasks)
        if (!shouldContinue) break
    }

    println("Bye!") // Bye!
}

And the help function, so the user doesn’t feel abandoned in the console, one-on-one with fate:

fun printHelp() {
    println("Commands:")
    println("  add <text>    — add a task")
    println("  list           — show tasks")
    println("  remove <...>   — remove by number or exact text")
    println("  exit           — exit")
}

Yes, there’s a mini list here. In help output, that’s normal: help without a list is like a microwave manual that says “you’ll figure it out.”

7. Common mistakes

Mistake #1: mixing up “number” and “index” and removing the wrong thing.
The most common bug with remove 2 is: the person thinks “second element,” but the code does removeAt(2) and removes the third, because list indexing starts at zero. Fix it with a simple rule: user number → index = number - 1, then check index in tasks.indices.

Mistake #2: checking bounds with index < size and forgetting negative values.
Beginners often write if (index < tasks.size) ... and forget that index can be -1, if the user enters remove 0. Checking via index in tasks.indices covers both sides at once and makes the code shorter, because the index range is already correct.

Mistake #3: removing list elements inside a for loop via tasks.remove(...).
If you try to remove elements directly from a collection during for (x in tasks), you may get skipped elements or a collection modification exception. For single deletion, it’s better not to traverse at all, but remove by index/value in one operation. For bulk deletion, use an iterator with it.remove().

Mistake #4: not distinguishing remove(value) and removeAt(index).
remove("milk") removes by value and returns a Boolean indicating success. removeAt(1) removes by position and returns the removed element. If you mix them up, the code either won’t compile or will behave differently than the user expects.

Mistake #5: not handling an empty argument for add and remove.
Commands without arguments are normal in real life: the user might press Enter too early or forget to finish typing. If you don’t check arg, you’ll either get empty tasks in the list or strange attempts to remove “nothing.” A simple check arg?.trim().isNullOrEmpty() makes behavior predictable and user-friendly.

Mistake #6: bloating main() into a “god method.”
It’s very easy to start writing everything right inside main: parsing, when, checks, printing, deletion, and a couple more “quick things.” After 20 minutes, you get a function that’s scary to touch because it “works, but I don’t know why.” It’s fixed by discipline: parsing separately, dispatch separately, operations separately. This is not “architecture for architecture’s sake”; it’s a way not to lose your mind on the first change of requirements.

1
Task
Kotlin SELF, level 20, lesson 4
Locked
Parsing a command
Parsing a command
1
Task
Kotlin SELF, level 20, lesson 4
Locked
Console dispatcher
Console dispatcher
1
Task
Kotlin SELF, level 20, lesson 4
Locked
Quote Box
Quote Box
1
Task
Kotlin SELF, level 20, lesson 4
Locked
Bookmark Manager
Bookmark Manager
1
Survey/quiz
Collection iteration, level 20, lesson 4
Unavailable
Collection iteration
Collection iteration
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION