From the Kotlin-documentation:
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = this.width * this.height
}
What I don't understand: How does the "get" know, that it belongs to "area"?
Especially if there would be another attribute, like let's say "length", which would have another "get". That would be two "get"-methods within the same class. How would the compiler know, which "get" belongs to which attribute?
If "val area" would be surrounded by braces, it would be clear to me. But the way it is I'm not sure how attribute and getter/setter are connected. Is it somehow white-space sensitive or similar?
Kotlin allows most of the tokens (that are the basic components your program consists of) to be separated by whitespace. That can be regular spaces, but usually linebreaks are also valid. The syntax is generally unambiguous enough so you do not even need a semicolon to terminate different statements.
In the example given the get
is an optional part of the val
declaration. It is just moved to the next line for clarity's sake. There is no syntactical ambiguity when you have multiple properties, each with their own get
.
This is how it would look like without linebreaks:
class Rectangle(val width: Int, val height: Int) {
val area: Int get() = this.width * this.height
val length: Int get() = max(this.width, this.height)
}
And this is exactly the same, just with linebreaks:
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = this.width * this.height
val length: Int
get() = max(this.width, this.height)
}
Additional linebreaks and indentation are ignored by the compiler, they are only used to make the code better readable for the human reader. They don't have any influence on the syntax at all.