Chapter 8. Static Methods to Top-Level Functions

Standalone functions are one of the fundamental building blocks of software. They have to be declared as methods on a class in Java, but in Kotlin we can declare them as top-level entities. When should we prefer top-level functions, and how do we refactor our way there from Java?

Java Statics

All values and functions in a Java program have to belong to a class: they are members of that class. Java calls member-values fields, and member-functions methods. By default, fields values are per-instance of the class: different instances have different values. Methods are also per-instance in that they have access to the state of the instance that they are invoked on. If we mark fields as static, though, they are shared between all instances of the class. Static methods only have access to this shared state (and visible static fields in other classes), but in return for this restriction, we can invoke them without needing an instance of the class.

To simplify Java, the language designers tied all code and data to classes. We have class-scoped static state, so we need class-scoped static methods. They could have added freestanding data and functions, but static fields and methods will do. If the language had options, then developers would have to choose between them, and less choice is often better. The designers then carried this language design decision forward to the Java Virtual Machine, which in turn has no way to express top-level ...

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.