Search code examples
classscalaparametersradix

computing base class parameters from derived class


I have the following problem (programming language: scala): A derived class D must compute base class parameters with a somewhat lengthy computation from its own parameters:

class D(a:Int,b:Int) extends B(f(a,b)) {...}  

Now I seem to have 3 possibilities:

(a) put the body of f(a,b) directly in the constructor of B: B({...})

(b) define f as a static function in the companion object of D

(c) define f as a member function of D which happens to be static

(a) Seems to be very inelegant. Are these approaches even legal? What would you do?

I am asking the question since I am starting out with scala and our organisation does not actually have scala installed yet so I can do experiments only intermittently at home.

Thanks for all replies.


Solution

  • Implement apply method in the companion object which transform constructor params in appropriate way

    object B {
      def f(a: Int) = a
    
      def apply(a: Int, b: Int) = new B(f(a), f(b))
    }
    

    If you need always transform constructor arguments think about correctness of your API. I suppose code review helps to make this code better.