Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala override java class method that references inner class

Tags:

java

scala

If I have the following class defined in java

public class A
{
  protected class B
  {
  }

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

And I want to inherit from it in scala and override method. 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:

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

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

like image 638
user79074 Avatar asked Nov 02 '22 11:11

user79074


1 Answers

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:

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.

like image 172
Hugh Avatar answered Nov 15 '22 04:11

Hugh