Trying to get the hang of Scala classes and traits, here's a simple example. I want to define a class which specifies a variety of operations, that could be implemented in lots of ways. I might start with,
sealed trait Operations{ def add def multiply } So for example, I might instantiate this class with an object does that add and multiply very sensibly,
case object CorrectOperations extends Operations{ def add(a:Double,b:Double)= a+b def multiply(a:Double,b:Double)= a*b } And also, there could be other ways of defining those operations, such as this obviously wrong way,
case object SillyOperations extends Operations{ def add(a:Double,b:Double)= a + b - 10 def multiply(a:Double,b:Double)= a/b } I would like to pass such an instance into a function that will execute the operations in a particular way.
def doOperations(a:Double,b:Double, op:operations) = { op.multiply(a,b) - op.add(a,b) } I would like doOperations to take any object of type operations so that I can make use of the add and multiply, whatever they may be.
What do I need to change about doOperations, and what am I misunderstanding here? Thanks