I just learned about the scalar to study rocket chips.
I see some strange codes in the Config.scala of Rocket-chip
abstract class Field[T] private (val default: Option[T])
{
def this() // 1st-this
= this(None) // 2nd-this
def this(default: T) // 3rd-this
= this(Some(default)) // 4th-this
}
The above code has 4 of this. I think 2nd/4th-this are identical.
But I'm not sure 2nd/4th-this are represent Field class self-type or not.
If they are self-type, 1st/3rd-this are to be what??
I'm frustrated since I can't tell the definition of the above four this.
Could you explain this?
CodePudding user response:
These are called auxiliary constructors (see https://docs.scala-lang.org/scala3/book/domain-modeling-tools.html#classes).
The "main constructor" is the one defined by the class declaration:
class Field[T] private (val default: Option[T])
With this you can create instances of Field
only by passing a Option[T]
. Like Field(None)
or Field(Some(...))
.
Then, you have 2 additional auxiliary constructors. They are defined as regular methods but they need to be called this
.
The following adds a constructor that accepts no parameter so that you can create instances with Field()
and it will be the same as Field(None)
. The 2nd this
refers to the main constructor.
def this() = this(None)
Same principle for the other auxiliary constructors which allows to call Field(x)
instead of Field(Some(x))
.
Note that you could achieve the same with apply
methods in a companion object.