Platform types help Kotlin work smoothly with Java code that may or may not allow null values. They let Kotlin be flexible when using Java libraries.
0
0
Platform types from Java interop in Kotlin
Introduction
When calling Java methods that can return null but don't specify it clearly.
When using Java fields or variables where nullability is not declared.
When you want Kotlin to trust Java code but still be careful about nulls.
When migrating Java code to Kotlin and handling unknown nullability.
When you want to avoid extra null checks but still keep safety in Kotlin.
Syntax
Kotlin
val example: String = javaMethod() val exampleNullable: String? = javaMethod()
Platform types appear when Kotlin calls Java code without nullability info.
You can treat platform types as nullable or non-nullable, but be careful to avoid null errors.
Examples
Kotlin assumes
getName() returns a non-null String, but it might be null in Java.Kotlin
val name: String = javaLib.getName()
You can also treat the platform type as nullable to be safe.
Kotlin
val nameNullable: String? = javaLib.getName()
If
getName() returns null, this will cause a crash because Kotlin thinks it's non-null.Kotlin
val length = javaLib.getName().lengthUsing safe call
?. avoids crash if the value is null.Kotlin
val lengthSafe = javaLib.getName()?.lengthSample Program
This example shows Kotlin calling a Java method that returns null but Kotlin treats it as non-null. It will crash at runtime.
Kotlin
class JavaLib { // Java method simulated in Kotlin for example fun getName(): String? = null } fun main() { val javaLib = JavaLib() // Platform type usage val name: String = javaLib.getName()!! // Simulates platform type usage println("Name length: ${name.length}") }
OutputSuccess
Important Notes
Platform types are Kotlin's way to handle Java's missing null info.
Be careful: treating platform types as non-null can cause crashes.
Use nullable types or safe calls to avoid errors.
Summary
Platform types appear when Kotlin calls Java code without nullability info.
They let Kotlin treat values as nullable or non-nullable but require caution.
Use safe calls or nullable types to avoid runtime crashes.