Platform types help Kotlin work safely with Java code that may or may not allow null values. They let Kotlin know when it should be careful about nulls.
Platform types and null safety in Kotlin
val someValue: String = javaMethod() val someNullableValue: String? = javaMethod()
Platform types appear when Kotlin calls Java methods without explicit nullability annotations.
You can treat platform types as nullable or non-nullable, but Kotlin warns you to be careful.
val name: String = javaGetName() // Platform type treated as non-null println(name.length)
val name: String? = javaGetName() // Platform type treated as nullable if (name != null) { println(name.length) }
val name = javaGetName() // Platform type, no explicit nullability println(name.length) // Risk of NullPointerException if null
This program simulates calling a Java method that returns null. Kotlin treats it as non-null, so accessing length causes a crash.
fun javaGetName(): String? = null // Simulate Java method that may return null fun main() { val name = javaGetName() // Platform type, no explicit nullability println("Name length: ${name!!.length}") }
Platform types let Kotlin be flexible but require you to be careful with nulls from Java.
Use explicit null checks or annotations in Java to improve safety.
When unsure, treat platform types as nullable to avoid crashes.
Platform types appear when Kotlin calls Java code without clear null info.
They can be treated as nullable or non-nullable, but this can cause risks.
Always check for null or add annotations to keep your Kotlin code safe.