简体   繁体   English

使用Android从Scala调用不同的Java父构造函数

[英]Call different Java parent constructor from Scala with Android

I need to inherit android.support.v4.view.ViewPager and two constructors. 我需要继承android.support.v4.view.ViewPager和两个构造函数。 In Java, it is done by: 在Java中,它通过以下方式完成:

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: 我在Google上搜索了一段时间,有些人建议在Scala中实现这个,如下所示:

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. 上面的Scala代码编译,但是当Android尝试构建视图时,似乎没有正确调用apply方法。 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 我认为这是因为当Android框架解析XML文件并尝试创建视图对象时,它使用反射来查找构造函数,因此它不使用apply方法

As LimbSoup and David himself have already said, this is just plain impossible in Scala. 正如LimbSoup和David本人已经说过的那样,这在Scala中根本不可能。 You will need to write the class in Java. 您需要用Java编写类。

So the bad news is, you will need some Java code. 所以坏消息是,你需要一些Java代码。

The good news is, the Scala compiler and most Scala tools have very good support for mixed Java/Scala codebases. 好消息是,Scala编译器和大多数Scala工具都非常支持混合Java / Scala代码库。 Java and Scala classes can freely inherit from each other and the compiler will figure it out just fine. Java和Scala类可以自由地相互继承,编译器会很好地解决它。 So you shouldn't find yourself in a situation where you're forced to write any substantial amount of code in Java. 因此,您不应该发现自己处于被迫用Java编写大量代码的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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