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

Fields and Methods

In this page:

  1. Fields and Methods

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())
}
🔒

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.