简体   繁体   中英

Call different Java parent constructor from Scala with Android

I need to inherit android.support.v4.view.ViewPager and two constructors. In Java, it is done by:

class MyViewPager extend android.support.v4.view.ViewPager {
  public ViewPager(Context context) {
    super(context);
  }

  public ViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
}

I have searched on Google and here for a while, and some people suggested to implement this in Scala like this:

import android.support.v4.view.ViewPager

trait ViewPagerTrait extends ViewPager {
  // ...implement ViewPager non-constructor functions here...
}

object MyViewPager {
  def apply(context: Context) = new ViewPager(context) with ViewPagerTrait
  def apply(context: Context, attrs: AttributeSet) = new ViewPager(context, attrs) with ViewPagerTrait
}

The above Scala code compiles, but it it seems that the apply method is not invoked correctly when Android tries to build the view. I think that's because when the Android framework parses the XML file and tries to create the view object, it uses reflection to find the constructor, thus it is not using the apply methods

As LimbSoup and David himself have already said, this is just plain impossible in Scala. You will need to write the class in Java.

So the bad news is, you will need some Java code.

The good news is, the Scala compiler and most Scala tools have very good support for mixed Java/Scala codebases. Java and Scala classes can freely inherit from each other and the compiler will figure it out just fine. So you shouldn't find yourself in a situation where you're forced to write any substantial amount of code in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM