Is it possible to create a secondary constructor without a macro annotation in Scala?

75 views Asked by At

I would like to create a macro that generates a secondary constructor{'s body). Is it possible to do this without resorting to macro annotations? (i.e. macro-paradise plugin)

For example:

Something like this:

class A(a : String, b : String) { 
  def this(s : List[Any]) = macro fromlist
}

Should be equivalent to something like this:

class A(a : String, b : String) {
  def this(s : List[Any]) = this(s.head.toString, s.tail.head.toString)
}

Simply using the "macro" keyword does not seem to help. Is this completely disallowed in plain Scala? Thanks.

1

There are 1 answers

1
dth On

The problem is, that a constructor is not a method returning a new instance, but a method initializing an already created one. (So the = in your constructor definition does not make sense, the parent constructor does not return anything).

The next problem is, that an alternative constructor in Scala has to call an other constructor as the first step, you cannot call something else, not even a macro.

You could however call a macro to generate the parameters to this, like

this(fromList(s): _*)

But why would you even want to do that? It is very uncommon in Scala to have multiple constructors. The common way is to have an overloaded apply method in the companion object. You don't have any restrictions there.