Skip to workspace
Kotlin Lab

Everyday Kotlin / Chapter 04

Narrow a scanner payload

Use a guard to make a nullable, unknown value safe to inspect.

The decision

A legacy scanner emits null, numeric device events, and strings. Accept only a string starting with PK- and at least one character after it. Return the suffix unchanged. For every other payload return null.

Read the Kotlin

Read the exits before the success path

The question mark in Any? admits a missing value. !is String tests the runtime type and also excludes null from the remaining path. After this early return Kotlin lets you call String methods on the stable parameter. For a scan with the right prefix, count its characters before taking the suffix. Letters, zeroes and further dashes in the suffix stay intact.

val raw = "PK-0-A"
raw.substring(3)  // "0-A", starting just after PK-

Separate a nullable target from a safe cast

The question mark has two jobs depending on its position. as String? permits a null result when the input itself is null. An integer still fails that cast at runtime. as? String turns a failed type check into null. An ordinary as String requires an actual non-null string.

val raw: Any? = 42
val label = raw as? String   // null
// raw as String?            // ClassCastException

Capture a reading before narrowing it

A property with a custom getter can fetch a new reading each time you mention it. The compiler cannot rely on the first check to narrow a later property read. Store one reading in a local val, then use that value for both checks and parsing. This also prevents consuming two events while handling one.

val event = reader.next
if (event is String) scanCode(event)

The full example

Java 25
class Lesson {
    static String scanCode(Object payload) {
        if (!(payload instanceof String text)) return null;
        if (!text.startsWith("PK-") || text.length() == 3) return null;
        return text.substring(3);
    }
}
Kotlin/JVM
fun scanCode(payload: Any?): String? {
    if (payload !is String) return null
    if (!payload.startsWith("PK-") || payload.length == 3) return null
    return payload.substring(3)
}

Inputs and outcomes

InputOutcomeWhy it matters
"PK-004""004"Keep leading zeroes in a package code.
42 or nullnullNeither payload is a String.
"PK-"nullThe prefix alone contains no code.

Walk through the code

  1. Any? admits both arbitrary objects and null. The !is String guard exits for both a device event and a missing value.
  2. After the guard Kotlin treats the stable parameter as a String, so startsWith and substring need no cast. Java 25 binds text in an instanceof pattern and tracks it after the early return.
  3. Only strip the prefix after checking that a suffix exists. Returning null exposes the absence to the Kotlin caller.

The Java habit

Checking a mutable property and then reading it again can observe a different value. Copy it into a local val and narrow that snapshot when both operations must inspect the same payload.

When to choose differently

If you control the decoder, a typed event hierarchy can retain the reason a reading was rejected. Any? is practical at a boundary where the upstream shape is genuinely unknown.

References

Open quizTry code