Question: Need help with a Scala code block please. Will upvote answer: object subtyping { // Instances of Counter have a integer field that can be
Need help with a Scala code block please. Will upvote answer:
object subtyping { // Instances of Counter have a integer field that can be incremented, decremented, or read. class Counter { private var n = 0 def increment () = { n = n + 1 } def decrement () = { n = n - 1 } def get () : Int = n } // EXERCISE 1: complete the following function. // The observeCounter function has one parameter f: a function that accepts (a reference to) a Counter instance but returns nothing. // The observeCounter function should call f with (a reference to) an object (of a class extending Counter). // Your class that extends Counter must keep track of the total number of times that increment/decrement have been called. // I.e., if the increment method is called 3 times on an instance, and the decrement method is called 2 times on the same instance, then it should store 5 (somewhere other than the existing field n). // observeCounter should call f, and then return the total number of times that increment/decrement were called on the instance by f. def observeCounter (f : Counter => Unit) : Int = { // TODO: Provide definition here. -1 } Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
