Scala

Scala Main class

Adding a main class is Scala is something that I always end up searching so next time it shall be through my blog.

You can go for the extends App option

One way is to add a main class by extending the App class. Everything else that get’s executed on that block is part of the “main” function.

1
2
3
4
5
6
package com.gkatzioura
 
object MainClass extends App {
 
  println("Hello world"!)
}

Then you can access the arguments since they are a variable on the App.

1
2
3
4
5
6
7
8
9
package com.gkatzioura
 
object MainClass extends App {
 
  for( arg <- args ) {
    println(arg)
  }
 
}

Add a main method

This is the most Java familiar option

1
2
3
4
5
6
7
8
9
package com.gkatzioura
 
object MainClass {
 
  def main(args: Array[String]): Unit = {
    println("Hello, world!")
  }
 
}

As expected you receive the program arguments through the function arguments.

01
02
03
04
05
06
07
08
09
10
11
package com.gkatzioura
 
object MainClass {
 
  def main(args: Array[String]): Unit = {
    for( arg <- args ) {
      println(arg)
    }
  }
 
}

Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Scala Main class

Opinions expressed by Java Code Geeks contributors are their own.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button