Reputation: 34673
This very simple worksheet content demonstrates the issue:
object Test {
println("This does not print!")
add(5, 6)
}
println("This however prints!")
add(5, 6)
def add(a: Int, b: Int): Int = a + b
Results from the above worksheet content are:
defined module Test
This however prints!
res0: Unit = ()
res1: Int = 11
add: add[](val a: Int,val b: Int) => Int
Based on JetBrains official website Scala Worksheets example and every other reliable resource I've found (like Martin Odresky's own examples in Functional Programming in Scala course), I would expect the contents of object Test
to execute. My software is:
Upvotes: 7
Views: 6852
Reputation: 399
I was able to evaluate the Scala work sheet by changing the Scala worksheet settings.
You can get to settings by clicking the settings icon on the Scala worksheet.
Upvotes: 15
Reputation: 31754
I think this is what you want:
object Test {
println("This does not print!")
add(5, 6)
println("This however prints!")
add(5, 6)
def add(a: Int, b: Int): Int = a + b
}
How the worksheet works is, that if you define an object and nothing defined outside the object
scope, it will execute it as Test extends App
. Which is what the intellij page displays
If you have any statement outside the object
scope, it is then treated as any other object
and compiler will initialize it like anything else. This is what you are experiencing.
Upvotes: 9
Reputation: 2101
The scala worksheet executes the contents of the object test{....} if all the code is inside that object. If there is some code outside the object, it will just define that Test object (and not run it).
object Test {
println("This does not print!")
def add(a: Int, b: Int): Int = {print("Sum:" + a + b); a + b}
add(2, 2)
}
// defined the above Test object
Test // executes the Test object
Upvotes: 9