Cannot run scala in IntelliJ

402 views Asked by At

I'm struggling with running Scala Hello World project using IntelliJ IDEA Scala plugin. The project is created without any problems but when I create function which should be run, the run button doesn't appear. I've got no idea why it doesn't work.

Version of IntelliJ - 2020.3.1 (Community Edition) Version of Scala plugin 2020.3.18

  1. I've created Scala/sbt project (I'd also tried Scala/IDEA)
  2. Vanilla options (but I'd also tried other versions of JDK, Scala and sbt)
  3. The run button is missing

My code is:

class Hello extends App {
  println("Hello world")
}

I've tried creating Scala worksheet and It works.

2

There are 2 answers

0
Suma On

When you extend App, it needs to be as object Main extends App, not class Main extends App.

See Scala 2.13 specification 9.5 (emphasis mine):

A program is a top-level object that has a member method main of type (Array[String])Unit

The main method of a program can be directly defined in the object, or it can be inherited. The scala library defines a special class scala.App whose body acts as a main method

0
Tomer Shetah On

As Suma mentioned in his answer, you should use object, and not class. The code of the Hello file should be:

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

As stated in YOUR FIRST LINES OF SCALA. Please note that if you prefer to extend App, all of the statements will be executed, as stated in the last link:

The argument of the scala command has to be a top-level object. If that object extends trait scala.App, then all statements contained in that object will be executed; otherwise you have to add a method main which will act as the entry point of your program.

Which means you have another option:

object Hello extends App {
  println("Hello world")
}

I have created a gif that shows an example.