WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 6 of 100

Explain the basic structure of a Scala program, including object, main method, and classes.?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

In Scala, a program can be composed of multiple objects, classes, and traits, but let’s start with the basic structure of a Scala program that includes an object, the main method, and classes.

1. Object: In Scala, an object is a singleton instance of a class. An object is created using the keyword ‘object‘. An object can extend classes or traits if needed. We usually define an object to create a singleton instance or to define utility methods.

Here’s an example of an object in Scala:

object MySingleton {
  def utilityMethod(): Int = {
    // Some business logic
    42
  }
}

2. Main Method: The main method is an entry point of a Scala program. The main method should have a specific signature: it should be a method named ‘main‘ that takes an array of strings as an argument and returns ‘Unit‘. The main method is usually defined inside an object.

Here’s an example of the main method in a Scala object:

object MyProgram {
  def main(args: Array[String]): Unit = {
    println("Hello, World!")
  }
}

3. Classes: A class in Scala is a blueprint for objects. It encapsulates data and methods that operate on that data. We create a class using the keyword ‘class‘. A class can have constructor parameters, fields, methods, and can also extend other classes and traits.

Here’s an example of a class in Scala:

class Person(name: String, age: Int) {
  def greet(): String = {
    s"Hello, my name is $name and I am $age years old."
  }
}

Now, let’s put everything together in a simple Scala program:

// Define the Person class
class Person(name: String, age: Int) {
  def greet(): String = {
    s"Hello, my name is $name and I am $age years old."
  }
}

// Define the main object with the main method
object MyProgram {
  def main(args: Array[String]): Unit = {
    // Create a new instance of the Person class
    val person = new Person("Alice", 30)
    
    // Call the greet method and print it
    println(person.greet())
  }
}

In this example, we defined a ‘Person‘ class and a ‘MyProgram‘ object. Inside the ‘MyProgram‘ object, we have the ‘main‘ method, which is the entry point of our program. Inside the ‘main‘ method, we create an instance of ‘Person‘ and call its ‘greet‘ method, printing the result to the console.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics