1

Hi I am new to scala and i am trying to execute a scala class from eclipse.
I have created a class and not object.

package classexample


class sample extends App {
  def printSample(): Unit = {
    println("Sample example")
  }

  def main(args: Array[String]) {
    val v = new sample;
    v.printSample()
  }

}

Now how do I execute this program.When I execute this this does not give any result.
Am i doing it in wrong way or i am missing something....Thanks for your help

6
  • How are you executing the program? Commented Aug 24, 2015 at 9:37
  • Just pressing the eclipse exeute button ..Not sure how to execute..This is exactly my question.. Commented Aug 24, 2015 at 9:38
  • 1
    All this does is define a class. There's no instance of the class, and nothing is executed. Note scala does not have static and so main is just a normal method. You need object, or to create an instance of the class Commented Aug 24, 2015 at 9:40
  • Can you please tell me what needs to be done here..can you please edit the answer... Commented Aug 24, 2015 at 9:44
  • 1
    Use an object! A different object that extends App if you want to then create an instance of your class. Commented Aug 24, 2015 at 9:45

1 Answer 1

2

When you have the Scala plugin installed in Eclipse, you can start an executable Scala in the same way you do for a Java executable. See scala-ide.org from info about this.

In Scala, you do not have to implement the 'main' method as for Java. Just extending the 'App' trait is sufficient. Any code in the constructor, which is all code in the class except val's, var's or def's, will be executed when the class is run.

Here an example of a runnable Scala class which prints 'Hello World'.

object RunnableScalaClass extends App {
  println("Hello World")
}
Sign up to request clarification or add additional context in comments.

2 Comments

The runnable must be an 'object' !! (I have updated the example). You should not add the 'main' method since it is not needed. You already extend 'App'.
The runnable must be on 'object' since Java's main class is also static : 'public static void main(String[] args)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.