问题
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