Skip to workspace
Kotlin Lab

Designing Kotlin APIs / Chapter 03

Pass a companion as a factory

Let a type own validation and supply a parser wherever a decoder is required.

The decision

A scanner accepts a badge code with exactly two uppercase ASCII letters, a hyphen and three digits. Callers need both Badge.parse(raw) and a reusable Decoder<Badge> for a batch importer. An invalid scan returns null.

Read the Kotlin

Read the companion in a value position

A companion is a single object associated with its enclosing class. Calling Badge.parse looks like a static Java call. Passing Badge where a Decoder is expected uses the companion object itself, which can implement an interface. The private constructor still controls which operations can make an actual Badge.

val decoder: Decoder<Badge> = Badge
val tag: Badge? = decoder.parse("AB-012")

Trace the entire scanned string

Kotlin Regex.matches requires the entire input to match. A substring search accepts a code embedded in extra characters. Trimming before validation introduces another change because a padded code becomes acceptable. Test a valid code, the same code with punctuation around it, and the same code with spaces before deciding which validation contract you want.

val format = Regex("[A-Z]{2}-[0-9]{3}")
format.matches("!AB-012")           // false
format.containsMatchIn("!AB-012")   // true

Choose who owns a decoder’s configuration

A single immutable pattern in a companion works when every importer accepts the same format. If two scanners accept different formats simultaneously, a mutable companion field gives them one setting to overwrite. Give each scanner a Decoder instance that owns its pattern and pass that object to the importer. Both can still use the same Decoder interface.

The full example

Java 25
import java.util.regex.Pattern;
import java.util.Optional;

class Lesson {
    interface Decoder<T> { T parse(String raw); }

    static final class Badge {
        final String text;
        private Badge(String text) { this.text = text; }

        private static final Pattern FORMAT = Pattern.compile("[A-Z]{2}-[0-9]{3}");
        static Badge parse(String raw) {
            return FORMAT.matcher(raw).matches() ? new Badge(raw) : null;
        }
        static final Decoder<Badge> DECODER = Badge::parse;
    }
}
Kotlin/JVM
interface Decoder<T> { fun parse(raw: String): T? }

class Badge private constructor(val text: String) {
    companion object : Decoder<Badge> {
        private val format = Regex("[A-Z]{2}-[0-9]{3}")
        override fun parse(raw: String): Badge? =
            if (format.matches(raw)) Badge(raw) else null
    }
}

Inputs and outcomes

InputOutcomeWhy it matters
AB-007Badge containing AB-007Preserve leading zeroes.
xAB-007ynullA match anywhere inside a longer scan is insufficient.
ab-007nullBadge codes are case-sensitive.

Walk through the code

  1. The private constructor makes parse the entry point that decides which strings become badges. matches checks the entire input and stores the original spelling when it succeeds.
  2. A companion object is an instance. It can own one compiled pattern and implement Decoder<Badge>. In a value position, the class name Badge denotes that companion, so val d: Decoder<Badge> = Badge compiles.
  3. Java’s static parse has no receiver instance. Its DECODER field supplies the interface value via a method reference. Both APIs can parse a string directly or receive a parser through dependency injection.

The Java habit

Writing object Badge would create a single badge value for every valid code. The companion is the shared parser; each successful parse constructs a badge for that particular input.

When to choose differently

When an importer has a different prefix list per tenant, a parser object configured for that importer is easier to reason about than changing global companion state.

References

Open quizTry code