Reputation:
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?
Upvotes: 1
Views: 458
Reputation: 8539
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)
Upvotes: 2
Reputation: 4587
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
})
Upvotes: 4
Reputation: 739
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
Upvotes: 1