Reputation: 43
I have to convert a Java code to Scala and use overriding on type. My Java code is:
public class StatementNode extends Node {
public StatementNode()
{
super(NodeType.statement);
}
protected StatementNode(NodeType type)
{
super(type);
}
My equivalent scala code is:
class StatementNode extends Node(NodeType.statement) {
protected def this(`type`: NodeType) {
super(`type`)
}
Works fine for Java but I found that scala does not supports super keyword. So how are we going to apply overriding for type in scala? Please help!Let me know if you need any other information.
Upvotes: 3
Views: 3567
Reputation: 9735
Adding to Michael's answer:
"Most generic" can also mean that one set of arguments can be derived from another. For example:
class Server(
listenPort: ListenPort,
authServerFactory: AuthServerFactory
) {
def this(
listenPort: ListenPort,
auth0Domain: String,
baseUri: URI
) = {
this(listenPort, AuthServerFactory(auth0Domain, baseUri))
}
...
}
In this case AuthServerFactory
can be created from two other arguments, but it might not be possible to do the other way around - deconstruct AuthServerFactory
into several arguments.
Upvotes: 0
Reputation: 55569
In Scala overloaded constructors have to call the most generic form of the class constructor, which must also be the default one. That is, you can't have a parameter-less constructor for StatementNode
, and then an overload that accepts a NodeType
as a parameter without calling the parameter-less default constructor (which couldn't work, anyway).
Instead you can do something like this:
class StatementNode protected (`type`: NodeType) extends Node(`type`) {
def this() = this(NodeType.statement)
}
You can make the default constructor protected
and have the NodeType
argument, and then provide an overload with no parameters that calls the main constructor and passes it NodeType.statement
. This should effectively do the same thing.
There is no need to call super
in Scala, because it is called through extends Node(
type)
, which is why the default constructor must contain the most generic form of the parameters.
Upvotes: 2