Skip to content

Commit 9a7633d

Browse files
update: Add section about constructor parameters and properties in classes (#4872)
* update: Add section about constructor parameters and properties Include a brief explanation between the difference between constructor parameters and properties in the constructor. * update: Update code example and explanation to include scope Co-authored-by: Sarah Haggarty <[email protected]> --------- Co-authored-by: Sarah Haggarty <[email protected]>
1 parent 163b13f commit 9a7633d

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

docs/topics/classes.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,24 @@ class Person(
9393

9494
Much like regular properties, properties declared in the primary constructor can be mutable (`var`) or read-only (`val`).
9595

96+
Plain constructor parameters (that are not properties) are accessible in:
97+
* The class header.
98+
* Initialized properties within the class body.
99+
* Initializer blocks.
100+
101+
For example:
102+
103+
```kotlin
104+
// width and height are plain constructor parameters
105+
class RectangleWithParameters(width: Int, height: Int) {
106+
val perimeter = 2 * width + 2 * height
107+
108+
init {
109+
println("Rectangle created with width = $width and height = $height")
110+
}
111+
}
112+
```
113+
96114
If the constructor has annotations or visibility modifiers, the `constructor` keyword is required and the modifiers go before it:
97115

98116
```kotlin

0 commit comments

Comments
 (0)