Jacobian
Jacobian

Reputation: 10882

Unable to run a HelloWorld Scala program on Ubuntu

I have my very first Scala program, which is as simple as:

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

I then try to compile it like so:

$ scalac HelloWorld.scala

And it compiles without any error messages. When however I try to run it like so:

$ scala HelloWorld

I get an error message:

No such file or class on classpath: HelloWorld

To implement this, I followed this tutorial and to solve the emerged error, I followed this suggestion. However,

$ scala objects.HelloWorld

also does not work. I know many people will now start heavily voting down my question and asking questions - have you ever tried to read some books on it (Yes, I did. I've read Horstman book for beginners, but it does not contain any information on compiling programs under Ubuntu). Still, I hope someone could help.

Upvotes: 1

Views: 535

Answers (2)

Mark Lewis
Mark Lewis

Reputation: 96

The answer saying that the scala command is just for the REPL is incorrect. You can see from the man page entry for scala (http://www.scala-lang.org/files/archive/nightly/docs-2.10.2/manual/html/scala.html) that it is intended to be used in the same way as the java command with the added flexibility that it will run the REPL, scripts, or compiled applications.

As some of the comments have indicated, this is almost certainly a path issue, which means that it requires more information to diagnose. One thing you can check is whether the scalac command produced a .class file in your current directory. If that is in the directory where you are running scala then the comments about needing . in your classpath are almost certainly correct.

Upvotes: 2

Madoc
Madoc

Reputation: 5919

(This was a comment before, and I rephrased it to a response.)

You've done everything right, except for the last step: Use the java command instead of the scala command.

scala is the Scala REPL. No separate run command is required for Scala code, because it compiles to regular Java bytecode.

So try: java HelloWorld

For more complex programs that make use of the Scala library however, you need to include the Scala runtime library in the classpath. So, on the long run, it is beneficiary to use a tool like SBT, as pointed out by @roterl in the comments.

Upvotes: 2

Related Questions