Program Structure
A basic Scala program lives inside an object that holds a starting spot called main. It is like a stage with a door marked 'the show begins here'.
In this page:
Syntax
object ObjectName {
def main(args: Array[String]): Unit = {
// program code
}
}
Program Structure
A basic Scala program is organized as an object containing a main method (or extending App), with statements executed in order.
The object Main extends App shorthand lets you write top-level statements directly in the object's body instead of wrapping them in an explicit main method. Both styles compile to a runnable program.
Note:
extends App is convenient for scripts and short programs, but explicit def main(args: Array[String]): Unit is more common in larger, production Scala code.Example: Program Structure
object Main {
def main(args: Array[String]): Unit = {
println("Program started")
greet()
println("Program finished")
}
def greet(): Unit = {
println("Hello from a helper method!")
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
def maininside aclassinstead of anobject, so Scala cannot find a static entry point. - Writing
def main(args: Array[String])with noUnitreturn type or a wrong signature, so the program does not run as an entry point. - Calling
greet()before it is defined and assuming order matters, when methods inside an object can be defined in any order.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: