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

Fields and Methods

Fields are the facts an object remembers and methods are the things it can do, like a dog that has a name and can bark. Adding val or var to constructor inputs turns them into fields.

In this page:

  1. Fields and Methods
Syntax
scala
class ClassName(val field1: Type, var field2: Type) {
  def method_name(param: Type): ReturnType = {
    // body
  }
}

Fields and Methods

Adding val or var before a constructor parameter, like class Point(val x: Int, val y: Int), exposes it as a public, read-only (or mutable, for var) field on instances.

Methods are defined with def inside the class body and can access these fields directly. Without val/var, a constructor parameter is only usable inside the class body, not accessible from outside.

Note: A constructor parameter without val/var is private to the class body -- add val to expose it as a public field.

Example: Fields and Methods

markup
class Rectangle(val width: Int, val height: Int) {
  def area(): Int = width * height
}

object Main extends App {
  val rect = new Rectangle(4, 5)
  println(rect.width)
  println(rect.area())
}
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. Declaring class Point(x: Int) and accessing p.x, which fails because without val the parameter is not a public field.
  2. Writing def area = width * height() mixing parentheses styles, when a method defined with () is called with ().
  3. Trying to assign a val field like rect.width = 10, when it needs var to be reassignable.
🔒

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.