= Solution
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 $[0,N)$ 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.<Scala 2.13 classes and objects specification>[Modifiers: private members are accessible to the enclosing template and its companion]{ref}
Back to article page