Mapping Effective Java Items to Kotlin: Items 1 to 4
This post provides a detailed classification of Effective Java items, focusing on how they translate — or don’t — into Kotlin. We’ll explore the status of each item and its relevance in the Kotlin world, highlighting key similarities, differences, and Kotlin-specific approaches.
Chapter 2: Creating and Destroying Objects
- Item 1: Consider static factory methods instead of constructors — Object creation in Kotlin can often look very different from Java, and many of the reasons in Effective Java for writing object creation APIs in particular ways are less applicable in Kotlin.
- Functions and constructors in Kotlin natively support named and optional parameters, which Effective Java cites as a key reason to use builders.
- It is possible to write pseudoconstructors in Kotlin, APIs that have exactly the same syntax as constructors but can have arbitrary implementations. Changing from a normal constructor to this kind of pseudoconstructor is a source-compatible change.
- Kotlin makes it trivial to write constructors that accept the properties of the class as arguments.
2. Item 2: Consider a builder when faced with many constructor parameters — obsolete
3. Item 3: Enforce the singleton property with a private constructor or an enum type —
- use object for singletons
4. Item 4: Enforce noninstantiability with a private constructor —
- use object for a namespace for utility methods. Also, the
sorts of methods that go in utility classes in Java often make more sense as extensions in Kotlin.