Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 12 / Topic 3 of 7

Platform types: the danger of String!

A platform type, written String! (you'll see this notation in IDE tooltips and compiler messages, never in source code you type), is what Kotlin assigns to a Java declaration with no nullability annotation at all. Kotlin genuinely doesn't know whether it can be null, so it lets you treat it as either — exactly like Java would — which means the null check is optional, not required, right up until it crashes:

val legacy = LegacyCarrierRates()
val note = legacy.operatorNote("Nagpur")   // operatorNote() has no annotation -- String!
println("Note length: " + note.length)      // compiles fine; no warning; no error

Running it, for real:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "note" is null
	at com.stepshala.carrier.PlatformTypeDangerKt.main(PlatformTypeDanger.kt:8)
	at com.stepshala.carrier.PlatformTypeDangerKt.main(PlatformTypeDanger.kt)

It compiled without a single warning and crashed the moment it actually ran, because "Nagpur" isn't in LegacyCarrierRates's map and operatorNote genuinely returns null for it. (The detailed "note" is null message comes from the JDK's helpful NullPointerException messages, not from Kotlin — Kotlin's own null-check instrumentation triggers it, but the JDK formats it.) Compare that to ratePerKgFor, which is @Nullable-annotated: Kotlin forces you to handle null with ?:/?. at the call site, at compile time, before the program ever runs — the exact crash above, prevented.

The fix for your own Kotlin code calling an unannotated Java method you can't change: treat the platform type as nullable yourself, explicitly, even though the compiler doesn't make you — val note: String? = legacy.operatorNote(city), then note?.length ?: 0.

Full file: examples/interop-project/PlatformTypeDanger.kt.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide