Chapter 11. Methods to Properties

Java does not distinguish between property access methods and other types. Kotlin, on the other hand, treats properties differently than member functions. When should we prefer a computed property to a function returning a result?

Fields, Accessors, and Properties

Most programming languages allow us to group data together in some way, giving names (and often types) to the properties of a composite.

Here, for example, is a record, composed of three fields, in ALGOL W, one of the first general-purpose languages to support record types. (ALGOL W was also the language in which Tony Hoare introduced null references.)

RECORD PERSON (
    STRING(20) NAME;
    INTEGER AGE;
    LOGICAL MALE;
);

Things were different then: real programmers only had CAPITAL LETTERS, and gender was a Boolean.

In ALGOL W, we can (well OK, could) update the age held in a PERSON record:

AGE(WILMA) := AGE(WILMA) + 1;

In this case the compiler will emit the instructions to reach into the memory of the record, find the bytes representing Wilma’s age, and increment it. Records, also known as structs (for structure) in other languages, are a convenience for grouping related data. There is no information hiding here, just composition.

Most early object-oriented systems (C++ in particular) were based on this record mechanism. Instance variables were simply record fields, and methods (aka member functions) were fields holding pointers to functions. Smalltalk was different. Smalltalk objects ...

Get Java to Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.