Extend Java abstract class in Scala

三世轮回 提交于 2021-01-05 07:31:22

问题


Given a Java class, something like

public abstract class A {
    public A(URI u) {
    }
}

I can extend it in Scala like this

class B(u: URI) extends A(u) { }

However, what I would like to do is alter the constructor of B, something like

case class Settings()

class B(settings: Settings) extends A {
  // Handle settings
  // Call A's constructor
}

What's the correct syntax for doing this in Scala?


回答1:


Blocks are expressions in Scala, so you can run code before calling the superclass constructor. Here's a (silly) example:

class Foo(a: Int)
class Bar(s: String) extends Foo({
  println(s)
  s.toInt
})




回答2:


You can achieve that in a very similar way to Object inside class with early initializer.

Assuming there is an abstract class A as declared above, you can do:

case class Settings(u: URI)

class B(s: Settings) extends {
  val uri = s.u
} with A(uri)

Then call:

val b = new B(Settings(new URI("aaa")))
println(b.uri)



回答3:


In Java "Invocation of a superclass constructor must be the first line in the subclass constructor." so, you can't really handle settings before calling A's c'tor. Even if it doesn't look like this all the initialization inside of class definition are actually constructors code. That's why there is no syntax for calling super's c'tor



来源:https://stackoverflow.com/questions/65276291/extend-java-abstract-class-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!