Scala Principles in a Nutshell (Part III)

Let’s say that we have the following code in Scala (too similar to Java, btw):

def isGoodEnough(inc:Int,x:Int)=x>inc;

def increasePosition(inc:Int,x:Int):Int=
    if (isGoodEnough(inc,x)) return x+inc;
    else return x;

def increasePositionByOne(x: Int) ={
    return increasePosition(1,x);
}

Now we’ll transform that piece of code into something more Scala-ish 😀

First of all, in Scala we don’t need the semi-colon:

def isGoodEnough(inc:Int,x:Int)=x>inc

def increasePosition(inc:Int,x:Int):Int=
    if (isGoodEnough(inc,x)) return x+inc
    else return x

def increasePositionByOne(x: Int) ={
    return increasePosition(1,x)
}

Second, we can ignore the return statement:

def isGoodEnough(inc:Int,x:Int)=x>inc

def increasePosition(inc:Int,x:Int):Int=
    if (isGoodEnough(inc,x))  x+inc
    else x

def increasePositionByOne(x: Int) ={
    increasePosition(1,x)
}

In case that the purpose of the methods isGoodEnough and increasePosition are to be used only in the method increasePositionByOne we can do nesting with them:


def increasePositionByOne(x: Int) ={
    def isGoodEnough(inc:Int,x:Int)=x>inc

    def increasePosition(inc:Int,x:Int):Int=
        if (isGoodEnough(inc,x))  x+inc
        else x

    increasePosition(1,x)
}

Is important to define the methods before use them in the rest of the code.

At this point the main method have the x parameter and at the same time, that parameter is defined again for each nested method. Scala allows to use a method parameter into nested ones without define it all over again. This is called Lexical Scope:


def increasePositionByOne(x: Int) ={
    def isGoodEnough(inc:Int)=x>inc

    def increasePosition(inc:Int):Int=
        if (isGoodEnough(inc,x))  x+inc
        else x

    increasePosition(1)
}

goto Part II
goto Part IV