Promoted Property
Script error: No such module "Draft topics".
Script error: No such module "AfC topic".
In object-oriented programming property promotion is a syntactic sugar which allows to reduce the amout of the code required to declare a class property and assign it in a class constructor. Currently it is supported in the PHP[1] and Kotlin[2] programming languages.
Languages which support promoted properties have special reserved words for declaring promoted properties (usually val or var). When an argument in a constructor is declared with such reserved word then it automatically declares a class property with the same name as the argument and automatically assigns the value of the argument to the property.
Examples[edit]
PHP 8.0[edit]
In PHP any constructor can have promoted properties. Such properties are marked with the one of the visibility keywords, e.g. public, protected etc:
class Photo {
public function __construct(
public string $fileName,
public int $width,
public int $height
) {}
}
The code above a shothand for the following code:
class Photo
{
public string $fileName;
public int $width;
public int $height;
public function __construct(
string $fileName,
string $width,
int $height
)
{
$this->fileName = $fileName;
$this->width = $width;
$this->height = $height;
}
}
Note: each property/argument name is repeated 4 times in the code while with property promotion it is required to specify only once.
Kotlin[edit]
In Kotlin only primary constructors can have promoted properties. Such properties are marked with the val or var keywords:
class Photo(val fileName: String, var width: Int, var height: Int) {
}
The code above is a shorthand for the following code:
class Photo {
val fileName: String
var width: Int
var height: Int
constructor(fileName: String, width: Int, height: Int) {
this.fileName = fileName
this.width = width
this.height = height
}
}
Note: each property/argument name is repeated 4 times in the code while with property promotion it is required to specify only once.
Depending on using var or val keywords the automatically generated properties will be either mutable or immutable respectively.
References[edit]
This article "Promoted Property" is from Wikipedia. The list of its authors can be seen in its historical and/or the page Edithistory:Promoted Property. Articles copied from Draft Namespace on Wikipedia could be seen on the Draft Namespace of Wikipedia and not main one.
- ↑ "PHP: rfc:constructor_promotion". wiki.php.net. Retrieved 2021-12-30.
- ↑ "Classes | Kotlin". Kotlin Help. Retrieved 2021-12-30.