So, I'm a bit new to Scala, and I don't really understand how it reads code, compared to other languages.
Take this simple example:
@main
def roll():Int =
var x:Int = (math.random*6 1).toInt
return x
def print =
for i <- 1 to 10 do
println(roll())
The above code returns nothing, however, should I flip the methods (put print "method" before "roll"), it will now work. I find this incredibly strange. Where have I done wrong? I just simply want to call a method/function that randomizes a number, and print it using a new function to call it. Anyone who can help me?
CodePudding user response:
@main
annotation is applied to method (one, the following after it), i.e. for :
@main
def roll():Int =
var x:Int = (math.random*6 1).toInt
return x
def print =
for i <- 1 to 10 do
println(roll())
Your main method will be roll
and only it will be invoked during program execution. And print
is just a declared method which is not called.
And when you "flip them":
@main
def print =
for i <- 1 to 10 do
println(roll())
def roll():Int =
var x:Int = (math.random*6 1).toInt
return x
print
becomes the main method, so it is invoked and it calls the declared roll
method in the loop.
Also read annotations doc.