Manu Chadha
Manu Chadha

Reputation: 16723

Why IntelliJ doesn't run my script if it has main in it

I am observing an interesting behavior. I have an existing project in which I created a folder and created a Scala script in that folder. To run it I did

  1. Write a Scala script, e.g. MyScript.scala
  2. In the menu select: Run -> Edit Configurations... Press the "+" (⌘N also works on the Mac in this dialog) Select "Scala Script" Then select your Script file in this dialog

Interestingly, if the script is the following then I get error Scala script not found

object HelloWorld{

  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}

but if the script is

def greetings(): Unit ={
  println("hello")
}


greetings();

then it works!

Why IntelliJ cannot run the 1st version of the script?

Upvotes: 1

Views: 316

Answers (1)

hce
hce

Reputation: 1167

You could do the following:

Run it as a script. You have to use the following code:

class HelloWorld {
  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}    
object Foo extends HelloWorld
Foo.main(args)

enter image description here

Hint: I removed the 'build' action from 'Before launch' to show the warnings further down.

Run it as an Application. You can keep your code. Just select 'Application' when creating the configuration.

object HelloWorld{

  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}

enter image description here

Why?

You have to provide an entry point for the script. So you could use the following code:

object HelloWorld {
  def main(args:Array[String]): Unit ={
    println("hello world");
  }
}
HelloWorld.main(args) //without this line, Script is not found!

But this gives an error (expected class or object definition):

enter image description here

An If you try to extend from App trait, you get 2 warnings:

object HelloWorld extends App {
  override def main(args:Array[String]): Unit ={
    println("hello world");
  }
}
HelloWorld.main(args)

enter image description here

So I guess its best to use one of two Solutions above.

Upvotes: 2

Related Questions