Classes and Objects

Scala supports traditional object-oriented concepts like classes and objects. Classes define blueprints; objects are singletons.

Defining a Class

class Person(val name: String, val age: Int) {
  def greet(): Unit = println(s"Hi, I'm $name and I'm $age years old")
}

Creating an Object

val p = new Person("Alice", 30)
p.greet()

Singleton Object

object MyUtils {
  def square(x: Int): Int = x * x
}

Use objects for utility methods or as the program entry point.

← PrevNext →