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:
Syntax
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
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())
}
Login to try C/C++/Java/PHP code in the editor
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
- Declaring
class Point(x: Int)and accessingp.x, which fails because withoutvalthe parameter is not a public field. - Writing
def area = width * height()mixing parentheses styles, when a method defined with()is called with(). - Trying to assign a
valfield likerect.width = 10, when it needsvarto be reassignable.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: