简体   繁体   English

scala覆盖引用内部类的java类方法

[英]scala override java class method that references inner class

If I have the following class defined in java 如果我在java中定义了以下类

public class A
{
  protected class B
  {
  }

  protected void method(B b) {...}
}

And I want to inherit from it in scala and override method. 我想在scala和override方法中继承它。 I would have hoped to do the following: 我本希望做到以下几点:

class C extends A {

  override def method(b: B): Unit = {
    // ... do something
    super.method(b)
  }
}

However the scala compiler does not like when I do it this way giving the following error: 但是scala编译器不喜欢我这样做时给出以下错误:

method method overrides nothing. 方法方法不会覆盖任何内容。 Note: the super classes of class C contain the following, non final members named method: protected[package ...] def method(x$1: A#B): Unit 注意:C类的超类包含以下非最终成员命名方法:protected [package ...] def方法(x $ 1:A#B):单位

The only way I can make it work is to do the following: 我能使它工作的唯一方法是执行以下操作:

class C extends A {

  override def method(b: A#B): Unit = {
    // ... do something
    super.method(b.asInstanceOf[this.B])
  }
}

I find having to do this quite ugly and was wondering if there was a neater way of doing it? 我发现必须做到这一点非常难看,并想知道是否有更简洁的方法吗?

Thanks 谢谢

Des

The obvious code works for me: 明显的代码对我有用:

public class A {
  public class B {}
  protected void method(B b) {
    System.out.println("A#method");
  }
}

class C extends A {
  override def method(b: B): Unit = {
    println("C#method")
    super.method(b)
  }
}

Then in the sbt console: 然后在sbt控制台中:

scala> new C
res0: C = C@10ecc87a

scala> new res0.B
res1: res0.B = A$B@db9a93b

scala> res0.method(res1)
C#method A$B@db9a93b
A#method A$B@db9a93b

However , if I then modify C.scala and get sbt to do an incremental recompile, I get the error you see (tested with 0.12.4 and 0.13.0) – it might be worth filing a sbt bug about this. 但是 ,如果我然后修改C.scala并让sbt进行增量重新编译,我会看到你看到的错误(用0.12.4和0.13.0测试) - 可能值得提一下这个错误。

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

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