Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compile Scala Hello World application

Tags:

scala

scalac

I'm new to Scala, and I've never written or compiled a program in it before. I'm trying to simply run the following Hello World example, which I have saved in a file name scalaApp.scala

object scalaApp extends App {
    def main(args: Array[String]) {
      println("Hello, world!")
    }
}

When I go the terminal in the file's directory and type "scalac scalaApp.scala", I get the following error message:

scalaApp.scala:4: error: overriding method main in trait App of type (args:    Array[String])Unit;
 method main needs `override' modifier
    def main(args: Array[String]) {
        ^
one error found

I thought I'd followed all the directions to install Scala 2.10.3 correctly on my computer, but I don't know how to test it since I can't even compile this simple program. If I type "scala" into the terminal I do get a scala prompt on which I can run commands like "1 + 1". I'm not sure how much that shows. I have added the SCALA_HOME variable to ~/.profile, and added SCALA_HOME to the PATH variable in ~/.profile. If anyone could tell me what I'm doing wrong, or give me a suggestion on where I might find an answer, I'd appreciate it.

like image 787
Steven Edmunds Avatar asked Jul 05 '14 04:07

Steven Edmunds


People also ask

How do I compile a Scala program?

To compile the code, type "scalac hello_world. scala" and press enter. You can see two class files HelloWorld$. class, HelloWorld.

How do I run a Scala program in notepad?

___ If we don't have version 1.8 or higher, Install the JDK Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (. scala) extension. open the command prompt follow step by step process on your system.


1 Answers

Since App extends DelayedInit, you shouldn't define a main function

This should be enough:

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

The compiler creates this function for you, and will pass it into the delayedInit(x: => Unit) method (notice the call-by-name in the parameter).

The compiler will emit:

object Main extends DelayedInit {
  def delayedInit(x: => Unit = { println("Hello, worl!") }) = // impl is left for us to fill in
}
like image 150
VonC Avatar answered Sep 23 '22 09:09

VonC