Fields and Methods
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: