Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run simple Scala class from terminal?

Tags:

scala

I have the Scala program myTest.scala with the following content:

class Test {
    def hello() {
        println("Hello, world!")
    }
}

How can I execute it from the console? If I run scala myTest.scala in the terminal, it obviously cannot find the main method which I do not have. Is there any way to run it as scala Test.hello? Is it mandatory to use scalac to compile before running scala?

like image 696
Markus Avatar asked Oct 19 '25 04:10

Markus


2 Answers

You need to first give your Object a main method. There are 2 ways to do this:

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

or

object HelloWorld extends App {
   println("Hello, world!")
}

Once you have your object ready. You can compile your class in your terminal as below:

$ scalac HelloWorld.scala

and run the program.

$ scala HelloWorld

More on this here.

like image 64
Rishu Shrivastava Avatar answered Oct 21 '25 18:10

Rishu Shrivastava


You can't run a class in Scala.

You need to define an object with a main method or that extends App

object Test extends App {
  println("Hello, world!")
} 
like image 31
Terry Dactyl Avatar answered Oct 21 '25 18:10

Terry Dactyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!