1

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?

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
jimera6624
  • 11
  • 2
  • Have you seen this: https://stackoverflow.com/questions/22363381/how-to-extend-an-abstract-class-in-scala-and-use-the-abstract-constructor – jmizv Dec 13 '20 at 13:46
  • @jmizv thanks, I did see that but I don't think it helps, as I can't change the Java class. – jimera6624 Dec 13 '20 at 13:50
  • You can ass an overload constructor in `B` or put that logic in an `apply` of the companion object. Also, you can make the primary constructor of `B` **private** to ensure users always use the alternative. – Luis Miguel Mejía Suárez Dec 13 '20 at 14:29

3 Answers3

4

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
})

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25
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)
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
1

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