Scala Objects
An object is a single named holder of fields and methods. The whole program shares that one holder and uses it by name.
An object holds fields
The Greeter object holds two fields. The main lines read them through the object name.
object Greeter:
val message = "Hello"
val times = 3
@main def main(): Unit =
println(Greeter.message)
println(Greeter.times)An object holds methods
The Shout object holds a method that makes a word upper case. Each call names the object first.
object Shout:
def shout(word: String): String = word.toUpperCase
@main def main(): Unit =
println(Shout.shout("hi"))
println(Shout.shout("scala"))An object can count its calls
The Counter object keeps a var count. Each next call raises the count by one and gives the new count back.
object Counter:
var count: Int = 0
def next(): Int =
count += 1
count
@main def main(): Unit =
println(Counter.next())
println(Counter.next())
println(Counter.count)Example
object Tickets:
var sold = 0
val price = 10
def sell(n: Int): Unit = sold += n
def total: Int = sold * price
@main def main(): Unit =
Tickets.sell(3)
Tickets.sell(2)
println(Tickets.sold)
println(Tickets.total)Key points
- Object: a single holder with one fixed name, defined with the object word.
- One only: a program has exactly one holder behind each object name.
- Fields: read an object field with the object name, a dot, and the field name.
- Methods: call an object method with the object name, a dot, and the method name.
- Var field: a var field inside an object keeps its latest value between calls.
In this example, the Tickets object holds a var count of tickets sold and a fixed price of 10. Two sell calls add 3 and then 2 to the count, so sold prints as 5. The total method multiplies 5 by 10, so the last line prints 50.
Note
an object is used by its name directly, and no value is created from it first.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
How many holders does a program have for one object, such as object Counter?