{{announcement.body}}
{{announcement.title}}

A Look at the Scala Main Class

DZone 's Guide to

A Look at the Scala Main Class

Check out this quick look at adding a main class in Scala.

· Java Zone ·
Free Resource

Check out this quick look at adding a main class in Scala.

Adding a main class in Scala is something that I always end up searching online, so next time, it shall be through this blog post! Let's get started.

You may also like: [DZone Refcard] Getting Started With Scala

Go for the Extends App Option

One way is to add aMainClass by extending theAppclass. Everything else that gets executed on that block is part of the "main" function.

Java




x


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



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

Java




xxxxxxxxxx
1
10
9


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




Add a Main Method

This is the most Java familiar option:

Java




xxxxxxxxxx
1


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



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

Java




xxxxxxxxxx
1
11


1
package com.gkatzioura
2
 
          
3
object MainClass {
4
 
          
5
  def main(args: Array[String]): Unit = {
6
    for( arg <- args ) {
7
      println(arg)
8
    }
9
  }
10
 
          
11
}



Hope you enjoyed! Please share your thoughts and questions in the comments section!

Further Reading

[DZone Refcard] Getting Started With Scala

Scala in a Java Maven Project

Making Spring Web Services With Scala

Topics:
java ,scala ,tutorial ,code ,main ,main method ,main class ,scala main

Published at DZone with permission of Emmanouil Gkatziouras , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}