ddinchev ddinchev - 2 months ago 39
Scala Question

Scala worksheet does not evaluate object in IntelliJ IDEA 2016.2

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:


  • OS X El Capitan

  • IntelliJ IDEA 2016.2

  • SBT Plugin 1.8.0

  • SBT Version 0.13.12

  • Scala Plugin 2016.2.1

  • Scala Version 2.11.8


Answer

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.