CodeGym /Courses /Kotlin SELF /Methods and state: behavior next to data, this, and basic...

Methods and state: behavior next to data, this, and basic checks

Kotlin SELF
Level 30, Lesson 2
Available

1. Why keep behavior next to data

When you start writing a program, you really want to keep all the logic “outside”: here’s the data, and separately there are functions that do something with it. And that’s fine — it’s easier to get started that way. But as the codebase grows, an unpleasant effect appears: the rules for working with the data start repeating in different places, and changes start to feel like a game of “find all the places where I forgot a check.”

Imagine we have an expense: a title and an amount. As long as you print it once, everything is fine. But as soon as you start renaming it, changing the amount, checking whether it’s a “large expense,” formatting the output — the logic gets smeared across the entire project.

This first looks roughly like this:

fun isLargeExpense(amount: Int): Boolean {
    return amount >= 1000
}

fun main() {
    val title = "Taxi"
    val amount = 1200

    println("$title: $amount")                 // Taxi: 1200
    println(isLargeExpense(amount))            // true
}

Does it work? Yes. Does it scale? Like a hacky “thesis project” — also yes, but not for long.

And this is where the idea shows up: if the “large expense check” is a meaningful part of an expense, why not make it an expense method?

2. Methods: declaration, invocation, and access to properties

Class method: how to declare and how to call

A method is a regular function, but it lives inside a class and is called on an object via dot syntax. In Kotlin, this reads very naturally: expense.isLarge() sounds like a phrase, not like an incantation from an ancient framework.

Let’s start with the simplest thing: add a method that prints an expense nicely as a single line.

class Expense(val title: String, val amount: Int) {
    fun asLine(): String {
        return "$title: $amount"
    }
}

fun main() {
    val e = Expense("Coffee", 300)
    println(e.asLine()) // Coffee: 300
}

Notice two things. First, a method is declared as fun inside the class’s curly braces. Second, it’s called as e.asLine(): object on the left, method on the right. This is an important habit, because almost all OOP in Kotlin will be “through the dot” from here on.

Why methods can “see” an object’s properties for free

The nicest part of methods for a beginner is that the method already “has the object in hand.” That is, you don’t need to pass title and amount separately, because they’re already inside the object. This looks like magic, but it’s really just logic: the method is called on a specific object, so it works with that object’s state.

Let’s compare two approaches — a function on the outside and a method on the inside.

Function outside:

class Expense(val title: String, val amount: Int)

fun asLine(e: Expense): String {
    return "${e.title}: ${e.amount}"
}

fun main() {
    val e = Expense("Lunch", 900)
    println(asLine(e)) // Lunch: 900
}

The same thing, but “next to the data”:

class Expense(val title: String, val amount: Int) {
    fun asLine(): String = "$title: $amount"
}

fun main() {
    val e = Expense("Lunch", 900)
    println(e.asLine()) // Lunch: 900
}

The second version is usually easier to read: less noise at the call site and less risk of “passing the wrong object.” And even more importantly — formatting rules live in one place, rather than spreading across the project.

3. Object state: var and the “object over time”

State is the current values of an object’s var properties. If an object has mutable fields, then the object can change over time: it was one way, then it became another. This is useful for counters, wallets, current settings, and generally anything that “lives” and changes.

Let’s make a mini example: a counter you can increment.

class Counter(var value: Int = 0) {
    fun inc() {
        value += 1
    }
}

fun main() {
    val c = Counter()
    c.inc()
    c.inc()
    println(c.value) // 2
}

And a very important detail that often breaks your brain at the beginning: val c = Counter() forbids reassigning the reference (that is, you can’t do c = Counter()), but it does not forbid changing the object’s state if there is a var inside.

So val does not make an object “frozen”; it makes a variable “non-reassignable.”

4. this: when you don’t need it and when it saves you

The word this in Kotlin means “the current object.” In most cases, Kotlin lets you omit it: if you access title, the compiler understands that it’s this.title.

But sometimes this is needed to remove ambiguity — especially when a method parameter has the same name as a property. This is a common case for “renaming,” “updating the amount,” and similar operations.

Here’s an example where this makes the intent unambiguous:

class Person(var name: String) {
    fun rename(name: String) {
        this.name = name.trim()
    }
}

fun main() {
    val p = Person("Ann")
    p.rename("  Anna  ")
    println(p.name) // Anna
}

The practical rule is simple: as long as there are no naming conflicts, you can omit this. As soon as you feel “something looks suspicious here,” this helps explicitly show that you’re changing the object’s state.

5. Invariants and checks: keeping an object in a valid state

An invariant is a simple rule for state correctness. In everyday terms: “what must always be true for the object to make sense.” For example, an expense amount must not be negative, and the title must not be empty.

It’s best to check invariants where the change happens — that is, in methods. Then you get a “single point of control,” and you don’t have to remember checks in every place in the program.

Let’s make Expense mutable and give it update methods with minimal checks:

class Expense(var title: String, var amount: Int) {

    fun rename(newTitle: String): Boolean {
        val t = newTitle.trim()
        if (t.isBlank()) return false
        title = t
        return true
    }

    fun changeAmount(newAmount: Int): Boolean {
        if (newAmount < 0) return false
        amount = newAmount
        return true
    }
}

Here the method returns Boolean, and that’s a very “down-to-earth” contract: true — it worked, false — it didn’t, and the object isn’t broken. This approach is good when an error is an expected part of life (the user typed nonsense — it happens).

Early return and require/check: different scenarios

Sometimes an error is a normal situation, and sometimes it’s a logical catastrophe (like “the wallet has a negative balance even though we promised that can’t happen”). Kotlin gives you two popular tools: a soft style with return false and a strict style with require/check.

  • require(...) usually validates input arguments and throws IllegalArgumentException on violation.
  • check(...) usually validates state and throws IllegalStateException on violation.

Let’s compare the approaches using a wallet example.

Soft variant (we expect the user can make mistakes):

class Wallet(var balance: Int) {

    fun withdraw(amount: Int): Boolean {
        if (amount <= 0) return false
        if (amount > balance) return false
        balance -= amount
        return true
    }
}

fun main() {
    val w = Wallet(100)
    println(w.withdraw(30))  // true
    println(w.balance)       // 70
    println(w.withdraw(200)) // false
}

Strict variant (we assume “you can’t come here with invalid data”):

class Wallet(var balance: Int) {

    fun withdraw(amount: Int) {
        require(amount > 0) { "Amount must be positive: $amount" }
        check(balance >= 0) { "Balance is broken: $balance" }

        require(amount <= balance) {
            "Not enough money. Balance=$balance, amount=$amount"
        }
        balance -= amount
    }
}

The difference is not syntax — it’s philosophy.

  • Returning false lets the program continue and calmly ask the user to “enter it again.”
  • require/check is a signal: “the program must not continue in this situation; it’s a contract violation.”

6. Applying it in practice: updating Expense via methods

We can already show the right idea with a small fragment: external code should not know all the rules for modifying an expense. External code should ask the object to perform an action, and the object itself decides what is allowed.

Here’s what updating the title can look like: instead of doing expense.title = ... directly, we call rename(...).

class Expense(var title: String, var amount: Int) {
    fun rename(newTitle: String): Boolean {
        val t = newTitle.trim()
        if (t.isBlank()) return false
        title = t
        return true
    }
}

fun main() {
    val e = Expense("Coffee", 300)

    val ok = e.rename("   ")
    println(ok)       // false
    println(e.title)  // Coffee
}

Notice that in case of an error, the object remains in its previous valid state. That’s a small “invariant win”: we didn’t allow creating a weird object that we wouldn’t know what to do with later.

If you want to update the amount too, external code again doesn’t “know” the rules — it just calls the method:

class Expense(var title: String, var amount: Int) {
    fun changeAmount(newAmount: Int): Boolean {
        if (newAmount < 0) return false
        amount = newAmount
        return true
    }
}

fun main() {
    val e = Expense("Taxi", 1200)

    e.changeAmount(1500)
    println(e.amount) // 1500
}

It looks like a small thing, but on a real project it saves a lot of nerves: you don’t search the entire codebase for “where could we have assigned a negative amount,” because you almost never do assignments “from the outside.”

7. Common mistakes

Error No. 1: the class exists, but all the logic still lives outside.
A beginner creates class Expense(...), but then continues writing a dozen functions like formatExpense(e), isLargeExpense(e), renameExpense(e, ...), validateExpense(e), etc. As a result, the class turns into a “bag of fields,” and the rules remain smeared around. If an action naturally belongs to a specific object, it’s better to make it a method: there’s less chance you’ll forget a rule in one of the places.

Error No. 2: mutability (var) is added “just in case,” not for a reason.
If you make all properties var, then any piece of code can change the object however it wants and whenever it wants. Then you suddenly see amount = -100 and start suspecting that dark magic has entered the project. It’s better to start with val, and add var only when the change is truly needed by the scenario’s meaning.

Error No. 3: state changes are made directly, bypassing methods.
You wrote rename() with checks, but somewhere in the code you still have expense.title = readln(). At that moment, the checks lose their meaning: some changes go through the “proper entrance,” and some through the “back door.” If you decided to protect invariants with methods, try to call methods rather than change fields directly.

Error No. 4: a method changes state but doesn’t report whether it succeeded.
If a method can “fail” (for example, the new title is empty) but returns Unit and silently does nothing, then external code doesn’t understand what happened. This creates weird scenarios: the user enters an empty string, the program continues as if everything is fine, but the change wasn’t applied. For expected errors, a Boolean contract is convenient: the caller can show a message and repeat the input.

Error No. 5: confusion due to identical names and missing this.
The method rename(name: String) will almost certainly appear in your life, and you will almost certainly once write name = name.trim() and stare at the monitor for a minute, waiting for enlightenment. In places like this, this is not “extra letters” — it’s a way to make the intent obvious: this.name = name.trim().

Error No. 6: require/check are used where the scenario should continue.
If you validate user input with require(...), then on an error your program will “crash” with an exception, because require works exactly that way. This is useful for enforcing a contract, but bad for a friendly CLI where the user might simply make a mistake. For expected errors, it’s better to return false/null and ask to re-enter, and reserve require/check for “this must not happen” situations.

1
Task
Kotlin SELF, level 30, lesson 2
Locked
Profile card
Profile card
1
Task
Kotlin SELF, level 30, lesson 2
Locked
Hero's Steps
Hero's Steps
1
Task
Kotlin SELF, level 30, lesson 2
Locked
Nickname without junk
Nickname without junk
1
Task
Kotlin SELF, level 30, lesson 2
Locked
Wallet of Rules
Wallet of Rules
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION