DDragon
DDragon

Reputation: 39

Confusing println output order

I am new to scala. When I run the following code:

object HelloWorld {

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

    println("1" + (1 to 4))

    println("2" + (1 to 4))

    Thread.sleep(100)

    for(x <- (1 to 4)) {

      println(inc(x) + " " + inc_sq(x, 4))

    }

  def inc(i:Int): Int = i + 1

  def inc_sq(i:Int, r:Int): Int = 

    (i+r) * (i+r)

}

I get the out put:

2Range(1, 2, 3, 4)
2 25
3 36
4 49
5 64
1Range(1, 2, 3, 4)

Why is it in such a disorder? I mean i think the last line of the actual output should be on the first line.

I am using Mac with Scala in Eclipse.

Upvotes: 1

Views: 103

Answers (1)

Arne Claassen
Arne Claassen

Reputation: 14404

You are missing a set of parentheses around your main block, causing only println("1" + (1 to 4)) to be the body of main. The rest is executed as part of the object Helloworld initialization. I believe, what you intended was this:

object HelloWorld {

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

    println("1" + (1 to 4))

    println("2" + (1 to 4))

    Thread.sleep(100)

    for (x <- (1 to 4)) {

      println(inc(x) + " " + inc_sq(x, 4))

    }
  }

  def inc(i: Int): Int = i + 1

  def inc_sq(i: Int, r: Int): Int =

    (i + r) * (i + r)

}

Upvotes: 7

Related Questions