Proper use of Scala traits and case objects -


trying hang of scala classes , traits, here's simple example. want define class specifies variety of operations, implemented in lots of ways. might start with,

sealed trait operations{   def add   def multiply } 

so example, might instantiate class object add , multiply 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 other ways of defining operations, such wrong way,

case object sillyoperations extends operations{     def add(a:double,b:double)= + b - 10     def multiply(a:double,b:double)= a/b } 

i pass such instance function execute operations in particular way.

 def dooperations(a:double,b:double, op:operations) = {    op.multiply(a,b) - op.add(a,b)  } 

i dooperations take object of type operations can make use of add , multiply, whatever may be.

what need change dooperations, , misunderstanding here? thanks

haven't ran code, suppose got compilation error.

if don't define signature of methods in operations trait, default interpreted () => unit.

this means methods in inheriting objects not overriding methods in trait, define overloads instead. see more here. can verify writing override in front of method definitions in object methods. force compiler explicitly warn methods not overriding ancestor trait, , works "safety net" against similar mistakes.

to fix bug, spell out signature of trait following:

sealed trait operations{   def add(a:double,b:double):double   def multiply(a:double,b:double):double } 

in fact, output parameter types not necessary in methods of inheriting objects (but note 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 }