0
0
Kotlinprogramming~7 mins

Platform types and null safety in Kotlin

Choose your learning style9 modes available
Introduction

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.

When calling Java code from Kotlin and you don't know if a value can be null.
When you want to avoid crashes caused by unexpected null values from Java libraries.
When mixing Kotlin and Java code in the same project and need safe null handling.
When you want Kotlin to help you catch possible null errors at compile time.
When you want to gradually add null safety to existing Java code.
Syntax
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.

Examples
Here, Kotlin assumes the Java method returns a non-null String, so you can use it safely.
Kotlin
val name: String = javaGetName()  // Platform type treated as non-null
println(name.length)
Here, Kotlin treats the Java return as nullable and checks for null before using it.
Kotlin
val name: String? = javaGetName()  // Platform type treated as nullable
if (name != null) {
    println(name.length)
}
If you ignore null safety, you might get a crash if the Java method returns null.
Kotlin
val name = javaGetName()  // Platform type, no explicit nullability
println(name.length)  // Risk of NullPointerException if null
Sample Program

This program simulates calling a Java method that returns null. Kotlin treats it as non-null, so accessing length causes a crash.

Kotlin
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}")
}
OutputSuccess
Important Notes

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.

Summary

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.