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

Part 03 / Topic 7 of 8

Platform types: an honest preview of Java interop

The moment Kotlin code calls a plain Java API with no nullability annotations, it meets a third kind of type: a platform type, shown in IDE tooltips as String!. Kotlin genuinely cannot know, from the method signature alone, whether the result can be null — so it lets the caller decide, by declaring the variable's type either way. That includes, dangerously, declaring it non-null when it can't actually guarantee that.

System.getenv(String) is a real example, straight from the Java standard library, with no Kotlin wrapper at all:

val configPath: String = System.getenv("APP_CONFIG_PATH")   // compiles. No warning. Still wrong.

Run it for real, for an environment variable that genuinely isn't set:

$ kotlinc PlatformTest.kt -include-runtime -d pt.jar
$ java -jar pt.jar
HOME = /Users/sujeet.s
Exception in thread "main" java.lang.NullPointerException: getenv(...) must not be null
	at PlatformTestKt.main(PlatformTest.kt:5)
	at PlatformTestKt.main(PlatformTest.kt)

(HOME itself prints a real value from this machine — machine-dependent, marked (varies) here deliberately; APP_CONFIG_PATH is the one that was never set, and that's the line that crashes.) The compiler accepted String for the declared type with zero warning, because a platform type carries no nullability information for Kotlin to check against. The crash is identical in shape to the Java NPE this whole part exists to prevent — platform types are exactly the seam where that protection can still be defeated, by a declaration, not by !!.

The fix: treat a platform type exactly like any other nullable type, the instant it enters Kotlin code, and let ?./?: work on it the same way they work on String? from Kotlin itself:

val home: String? = System.getenv("HOME")        // the honest declaration
println("HOME = ${home ?: "not set"}")
$ kotlinc 07_platform_types.kt -include-runtime -d 07.jar
$ java -jar 07.jar
HOME = /Users/sujeet.s
missing var = not set
HOME length = 15

(Again, the HOME value and its length are (varies) — specific to this machine, not a fixed fact about Kotlin.)

🔍 Going deeper: this is a preview, not the full story. Stage 2, Part 12 ("Java interop and the JVM ecosystem") covers calling a real Java class from Kotlin, exposing Kotlin to Java, and the @Nullable/@NotNull annotations that turn a platform type back into a real one — once there's an actual mixed-language build to point at (see ../../DESIGN-NOTES.md for why interop waits until Part 12).

Full program: examples/07_platform_types.kt.

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

Search the guide