Avinash
Avinash

Reputation: 13257

Scala : statements are not executed in order

I am learning scala I tried following program

package com.avdongre

object MyModule {
  def abs(n: Int): Int =
    if (n < 0) -n
    else n
  private def formatAbs(x: Int) = {
    val msg = "The absolute value of %d is %d"
    msg.format(x, abs(x))
  }

  def factorial(n: Int): Int = {
    def go(n: Int, acc: Int): Int =
      if (n <= 0) acc
      else go(n - 1, n * acc)
    go(n, 1)
  }
  def main(args: Array[String]): Unit =    
    println(formatAbs(-42))
    println(factorial(5))

}

I get following output

120
The absolute value of -42 is 42

Why factorial is getting called first ?

Upvotes: 1

Views: 88

Answers (1)

joescii
joescii

Reputation: 6533

You need curly braces around your body of main:

def main(args: Array[String]): Unit = {
  println(formatAbs(-42))
  println(factorial(5))
}

What is happening is you have this (with corrected indentation for clarity):

def main(args: Array[String]): Unit = 
  println(formatAbs(-42))

println(factorial(5))

Hence when the object MyModule gets initialized, the last statement of the body is println(factorial(5)) which occurs before your main method.

Upvotes: 6

Related Questions