Skip to content
Anjunar/ DOCS

Constructors and parameters

Every constructor comes with its parameters: name, type, annotations and whether a default value exists. That is what a factory needs to call a constructor without guessing.

Parameters

Names, types and defaults

hasDefault says whether the caller may leave a parameter out. The primary constructor is marked, so secondary constructors do not get in the way.

number
java.lang.String
amount
scala.math.BigDecimal · has default
currency
java.lang.String · has default
scala
case class Invoice(number: String, amount: BigDecimal = BigDecimal(0), currency: String = "EUR") val primary = ReflectMacros.reflect[Invoice].constructors.find(_.isPrimary).get primary.parameters.map(parameter => parameter.name -> parameter.hasDefault)
Several constructors

Primary and secondary

A class with auxiliary constructors lists all of them. isPrimary tells them apart, parameterNames and parameterCount describe each.

(x, y)
primary
scala
class Point(val x: Int, val y: Int) { def this(both: Int) = this(both, both) } ReflectMacros.reflect[Point].constructors.map(c => c.parameterNames.toList -> c.isPrimary)
Creating

From parameters to an instance

The descriptor describes; it does not call. Create case classes with createInstance, other classes through a factory bound to the descriptor.

ReflectMacros.createInstance[Invoice]("R-1", BigDecimal(90), "EUR")
Invoice(R-1,90,EUR)
Defaults are not applied

hasDefault tells you a default exists, and defaultIndex which one; createInstance still needs every argument. Pass the values yourself when you build instances from partial input.