Vivek - 3 months ago 9

Scala Question

I am very new to Scala. I tried calling formatResult inside println 3 times from main passing abs, fact, fib in that order.

But the output shows a different execution order - fact, fib, abs

/* MyModule.scala */

`object MyModule {`

def abs(n: Int): Int =

if(n < 0)

-n

else

n

def fact(n: Int): Int = {

def go(n: Int, acc: Int): Int = {

if(n <= 1)

acc

else

go(n - 1, n * acc)

}

go(n, 1)

}

def fib(n: Int): Int = {

def loop(n: Int, prev: Int, curr: Int): Int = {

if(n == 0)

prev

else

loop(n - 1, curr, prev + curr)

}

loop(n, 0, 1)

}

private def formatResult(fName: String, placeholder: String, n: Int, f: Int => Int) = {

val msg = "The %s %s %d is %d"

msg.format(fName, placeholder, n, f(n))

}

def main(args: Array[String]): Unit =

println(formatResult("absolute value", "of", -10, abs))

println(formatResult("factorial", "of", 5, fact))

println(formatResult("fibonacci number", "at index", 8, fib))

}

/* output */

`The factorial of 5 is 120`

The fibonacci number at index 8 is 21

The absolute value of -10 is 10

Could someone please explain this to me?

Answer

Your main method code is not surround by braces. So your main method becomes just the following:

```
def main(args: Array[String]): Unit =
println(formatResult("absolute value", "of", -10, abs))
```

The other two print lines are executed as the object is setup. So they run before the main method is called. The following will work correctly:

```
def main(args: Array[String]): Unit = {
println(formatResult("absolute value", "of", -10, abs))
println(formatResult("factorial", "of", 5, fact))
println(formatResult("fibonacci number", "at index", 8, fib))
}
```