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?

3
  • Have you seen this: stackoverflow.com/questions/22363381/… Commented Dec 13, 2020 at 13:46
  • @jmizv thanks, I did see that but I don't think it helps, as I can't change the Java class. Commented Dec 13, 2020 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. Commented Dec 13, 2020 at 14:29

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.