Start learning free

LESSON 84 OF 414 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating abs() in Scala: if and else

Practice Read the full explanation

The abs() function returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function abs() that recreates this functionality.

Examples:

abs(-12) ➞ 12

abs(-544) ➞ 544

abs(250) ➞ 250

abs(0) ➞ 0

abs(-14) ➞ 14

Note:

Do not use the abs() function provided by Scala (it will defeat the purpose of the challenge)


Hints:


You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in Scala, explained

    Problem overview

    The absolute value of a number is its distance from zero, so it is never negative. The method abs receives an Int named n and returns n without its sign: -5 becomes 5, 5 stays 5, and 0 stays 0. The task is to build this yourself, without calling the abs function that Scala provides.

    The method takes and returns an Int, so the code below works on whole numbers. The logic is the same for any numeric type, decimals included.

    Approach: only negatives change

    Positive numbers and zero are already their own absolute value. Only a negative number has to change, and the change is one operation: negate it. Negating a negative number gives a positive one, because -(-5) is 5.

    That gives a two-way decision, which is exactly what if and else express: if n is below zero, return -n; otherwise return n.

    Step by step

    1. Test for a negative number. Write an if whose condition is n < 0. Leave the body empty for the moment.
    2. Negate inside the if. Return -n. The unary minus flips the sign, so a negative input produces a positive result.
    3. Handle everything else. Add } else { on one line after the if body, and return n unchanged. Zero lands in this branch, which is correct, since the absolute value of 0 is 0.

    The solution in Scala

    class Solution {
        def abs(n: Int): Int = {
            if (n < 0) {
                return -n
            } else {
                return n
            }
        }
    }
    

    The Scala details worth knowing:

    • Return type. The signature def abs(n: Int): Int declares the type of the result. A method that uses return must declare its result type (leaving it out is a compile error), and the compiler checks that both branches produce an Int.
    • return is optional. In Scala the last expression of a block is its value, and if/else is itself an expression. The same method can be written as if (n < 0) -n else n, and this is the usual style. The lesson's version with explicit return behaves identically.
    • Unary minus. -n is a method call on the integer, written with the operator syntax. It works on any numeric type.

    Edge cases and common mistakes

    • Zero. abs(0) returns 0. Whether zero goes to the if or the else branch gives the same answer, but writing n <= 0 is unnecessary.
    • Forgetting the else. If the method has only the if with a return and nothing after it, the compiler reports a type mismatch (found Unit, required Int) and hints that an else part is missing, since a non-negative input would have no value to produce.
    • Returning n in the first branch. Returning the input unchanged when it is negative gives back the negative number.
    • The smallest Int. Int has 32 bits, and its range is not symmetric: the minimum is -2147483648 while the maximum is 2147483647. So -n for n = Int.MinValue overflows silently and the result is still -2147483648. For ordinary inputs this never matters, but it is the one value where this method returns a negative number.

    Testing

    • abs(-5) gives 5.
    • abs(250) gives 250.
    • abs(0) gives 0.
    • abs(-1) gives 1.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free