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
?
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
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!")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With