3

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

0

1 Answer 1

5

Haven't ran your code, but I suppose you got a compilation error.

If you don't define the signature of the methods in the Operations trait, then by default it will be interpreted as () => Unit.

This means that the methods in the inheriting objects are not really overriding the methods in the trait, but define overloads instead. See more about that here. You can verify this by writing override in front of the method definitions in the object methods. That will force the compiler to explicitly warn you that the methods are not overriding anything from the ancestor trait, and works as a "safety net" against similar mistakes.

To fix the bug, spell out the signature of the trait like the following:

sealed trait Operations{ def add(a:Double,b:Double):Double def multiply(a:Double,b:Double):Double } 

In fact, the output parameter types are not even necessary in the methods of the inheriting objects (but note the added override attributes):

case object CorrectOperations extends Operations{ override def add(a:Double,b:Double) = a+b override def multiply(a:Double,b:Double) = a*b } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So your second code block there isn't working for me, override def add = a+b, it appears I still need the signatures...
@keegan sorry, indeed you are right, it needs the input parameters... but not the output. See edited version.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.