Chapter 7. Actions to Calculations

Neither Java nor Kotlin makes any formal distinction between imperative and functional code, although Kotlin’s emphasis on immutability and expressions generally leads to more functional programs. Can we improve our code by making more of it functional?

Functions

As an industry, we have invented a lot of phrases to describe callable subprograms within a larger program. We have the very generic subroutine. Some languages (notably Pascal) distinguish between functions that return a result, and procedures, which don’t; but most developers use the terms interchangeably. Then there are methods, which are subroutines associated with an object (or a class, in the case of static methods).

The C language calls them all functions but has a special void type to represent the absence of a return value. This was carried forward into Java. Kotlin uses Unit in almost the same way, except that Unit is not the absence of a return value, but rather a singleton value that is returned instead.

In this book we use the term function to refer to both result-returning and non-result-returning subroutines, whether freestanding or associated with an object. Where it’s significant that they are associated with an object, we’ll call them as methods.

Whatever we call them, functions are one of the fundamental building blocks of our software. We define them with some sort of notation, generally the programming language we are using. They are also generally fixed during ...

Get Java to Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.