← Back to Scala Course | Chapter 1: Setup & Basics | Lesson 5 of 8

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:

  1. Program Structure
Syntax
scala
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

markup
object Main {
  def main(args: Array[String]): Unit = {
    println("Program started")
    greet()
    println("Program finished")
  }

  def greet(): Unit = {
    println("Hello from a helper method!")
  }
}
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
  1. Writing def main inside a class instead of an object, so Scala cannot find a static entry point.
  2. Writing def main(args: Array[String]) with no Unit return type or a wrong signature, so the program does not run as an entry point.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.