← Back to Scala Course | Chapter 7: OOP Basics | Lesson 1 of 7

Class Basics

A class is a blueprint that describes what things of one kind know and can do, like the plan for a toy car. You use it to make as many toy cars as you want.

In this page:

  1. Class Basics
Syntax
scala
class ClassName {
  // fields
  // methods
}

val instance = new ClassName

Class Basics

A Scala class is declared with class ClassName { ... }, bundling data and behavior into a blueprint you instantiate with new.

Unlike some languages, a class's primary constructor parameters can be declared directly in the class signature, like class Point(x: Int, y: Int). Every value in Scala, including numbers, is technically an object of some class.

Note: Constructor parameters declared directly in the class signature avoid needing a separate explicit constructor block for the common case.

Example: Class Basics

markup
class Dog(name: String) {
  def bark(): Unit = {
    println(s"$name says Woof!")
  }
}

object Main extends App {
  val rex = new Dog("Rex")
  rex.bark()
}
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. Creating an object without new in Scala 2, as in Dog("Rex") for a plain class, which does not compile; only case classes get apply.
  2. Calling rex.name for a plain constructor parameter, which is private to the class unless declared as val.
  3. Using class Dog { def bark = ... } inside object Main extends App and forgetting to instantiate it before calling its methods.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.