AI Briefing
KO

Code Quality Improvement - Session 64: Keeping Primary Constructors Simple

·2026.01.30 12:00

Key point

Kotlin primary constructors should be kept simple to match the class's properties, with complex logic separated into secondary constructors or factory functions.

Details

Kotlin's Primary Constructor is best designed to match the class's properties as closely as possible. Performing complex operations such as parsing or conversion inside the constructor can make the class's structure hard to grasp and obscure the design intent.

Keeping the constructor simple has the advantage of allowing the use of data class. Complex object creation logic should be separated and managed using the following approaches.

  • Secondary Constructor: Suitable when simple data conversion is needed.
  • Factory Function: Useful when complex logic is required, when null needs to be returned on creation failure, or when an instance of a subclass of a specific interface needs to be returned.

A Constructor-like factory function with the same name as the class can also be used to separate the interface from its implementation, but since it is not an actual constructor, it can cause confusion, so its use should be avoided in general application code.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.