Start learning free

LESSON 75 OF 348 · CONDITIONAL STATEMENTS

Reducing If-Else to a Boolean Expression in Kotlin

Practice Read the full explanation

We will learn a simple trick to improve our code quality: Reducing If-Else to Boolean Expressions.

Video Lesson:

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    Reducing If Else To Boolean Expression in Kotlin, explained

    Problem overview

    The function legalAge(age: Int): Boolean must return true when age is at least 18 and false otherwise. The lesson asks for it in a single line of code, with no if and no else.

    For example, legalAge(20) is true, legalAge(18) is true and legalAge(17) is false.

    Approach

    The straightforward version uses an if to pick between two literals:

    fun legalAge(age: Int): Boolean {
        if (age >= 18) {
            return true
        } else {
            return false
        }
    }
    

    It works, but look at what it says: "if this condition is true, return true, otherwise return false". The returned value is always the same as the condition's own value. The condition age >= 18 already is a Boolean. When it is true, you return true, and when it is false, you return false. So the if and the else only repeat the answer that the comparison has already produced.

    The cleaner version returns the comparison itself.

    Step by step

    1. Write the comparison. The rule "at least 18" is age >= 18. The operator includes 18, so a person who is exactly 18 counts as legal.
    2. Return it. Put return in front. A comparison is an expression with a Boolean value, so it can be returned like any other value.

    The solution in Kotlin

    class Solution {
        fun legalAge(age: Int): Boolean {
            return age >= 18
        }
    }
    

    Kotlin details:

    • The return type matches. The function is declared to return Boolean, and age >= 18 is a Boolean, so the compiler accepts it.
    • No parentheses are needed. The comparison is evaluated first and then returned.
    • Single-expression form. Kotlin lets a function whose body is one expression be written as fun legalAge(age: Int): Boolean = age >= 18. The lesson uses the usual block form with return.

    The same trick elsewhere

    Once you spot the pattern, you will see it often. Any function that answers a yes-or-no question can return the test directly:

    fun isEven(n: Int): Boolean = n % 2 == 0
    fun isTeen(age: Int): Boolean = age >= 13 && age <= 19
    fun isMinor(age: Int): Boolean = !(age >= 18)
    

    Here isEven(4) is true and isEven(7) is false. isTeen(13) is true and isTeen(20) is false. isMinor(17) is true and isMinor(18) is false. The ! operator turns true into false and the other way round, so !(age >= 18) means the same as age < 18.

    The benefit is not only fewer lines. A short expression leaves less room for mistakes, such as returning true from the wrong branch, and a reader can see the rule at a glance.

    How to spot the pattern

    Look for an if whose branches do nothing except return, assign or print the literals true and false. Whenever you see if (condition) return true else return false, the whole statement can be replaced by return condition. Trace it once to be sure: with age = 20 the comparison 20 >= 18 evaluates to true and that value is returned; with age = 5 it evaluates to false and that is returned. Both results match the long version, which is exactly what a safe simplification must do: change the form of the code and nothing about its behaviour.

    Edge cases and common mistakes

    • The boundary. legalAge(18) is true. Using > instead of >= would make it false.
    • Returning a string. The function returns a real Boolean, not the text "true".
    • Comparing to a literal. Writing return (age >= 18) == true is correct but pointless. The comparison is already the answer.
    • Reducing when the branches differ. This shortcut only applies when the two branches return the literals true and false. If they return something else, such as strings, an if is needed.
    • Reversed results. If an old if returned false in the true branch, the shortcut returns the opposite of the condition. For that case, write the condition with ! or flip the comparison, for example age < 18.

    Testing

    • legalAge(17) returns false.
    • legalAge(18) returns true.
    • legalAge(30) returns true.
    • legalAge(0) returns false.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free