marbarfa
marbarfa

Reputation: 677

Scala - custom class constructors

I have a simple question but couldn't find the answer anywhere.

I have the following java code. FrameLayout is an android class that has 2 constructors:

public class FrameLayout {
  public FrameLayout(Context context){ //do something
  }
  public FrameLayout(Context context, AttributeSet attrs){ //do something
  }
  ....
}

public class ClassA extends FrameLayout{
  public ClassA(Context c){ 
      super(c);
      callSomeInitMethod();
  }

  public ClassA(Context a, AttributeSet b){ 
        super(a,b);
        callSomeInitMethod();
  }
}

I have the following scala code but it's not the same as the default constructor doesn't call the 'callSomeInitMethod()':

abstract class BaseComponent(context : Context, attrs : AttributeSet)
                                 extends FrameLayout(context, attrs) {
  def this(context : Context) = {
    this(context, null)
    callSomeInitMethod()
  }

How to I implement this in Scala?. Thanks!.

Upvotes: 0

Views: 318

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

Just put the call to callSomeInitMethod into the class body. This makes it part of the main constructor (and hence, of all the secondary constructors):

abstract class BaseComponent(context : Context, attrs : AttributeSet)
    extends FrameLayout(context, attrs) 
{
  callSomeInitMethod()

  def this(context : Context) = {
    this(context, null)
  }
}

Upvotes: 2

Related Questions