Companion object 2026-10-31
In Scala, a singleton object associated with a same-named companion class in the required source context. Object members and instance members are distinct:
B.g(x) invokes a member of object B, while b.g(x) invokes an instance member through b. Both can use method overloading, but the instance's members are not automatically part of the companion's overload set.[ref]The following method belongs inside the source class and uses the helper from part (d). It preserves the existing outgoing count, and a newly encountered user starts with exactly one incoming and zero outgoing payments.
def recordIncoming(user: Int): Unit = {
require(1 <= user && user <= 99999999, "invalid user identity")
val bucket = hash(user)
val p = find(user, table(bucket))
if (p == null) {
table(bucket) = new PaymentsHash.Node(user, 1, 0, table(bucket))
} else {
require(p.countIn < Int.MaxValue, "incoming count is full")
p.countIn += 1
}
}On a hit, exactly one field is incremented after the overflow check. On a miss, inserting at the bucket head preserves all existing records and gives precisely the required change from implicit zero to one. The given hash function must return an index in consistently for a given user. Its actual formula is not needed by this method. The nested private node class is accessible to its companion class in Scala, so retaining the source's
PaymentsHash.Node visibility is valid.[ref]Scala 2.13 classes and objects specification. Modifiers: private members are accessible to the enclosing template and its companion