A Look at the Scala Main Class
Check out this quick look at adding a main class in Scala.
Join the DZone community and get the full member experience.
Join For Free
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 theApp
class. Everything else that gets executed on that block is part of the "main" function.
package com.gkatzioura
object MainClass extends App {
println("Hello world"!)
}
Then, you can access the arguments since they are a variable on the App
.
xxxxxxxxxx
package com.gkatzioura
object MainClass extends App {
for( arg <- args ) {
println(arg)
}
}
Add a Main Method
This is the most Java familiar option:
xxxxxxxxxx
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.
xxxxxxxxxx
package com.gkatzioura
object MainClass {
def main(args: Array[String]): Unit = {
for( arg <- args ) {
println(arg)
}
}
}
Hope you enjoyed! Please share your thoughts and questions in the comments section!
Further Reading
Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments