A platform type is a Java type whose declaration provides no nullability information. Kotlin lets you use it as either nullable or non-nullable, preserving Java interoperability while placing responsibility for null handling on you. Java annotations such as @Nullable and @NotNull remove this ambiguity by becoming Kotlin's String? and String types. section 7.12 section 7.12.1
Choosing how to read an unannotated Java property
/* Java */ public class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } } // Kotlin fun yellAt(person: Person) { println(person.name.uppercase() + "!!!") } fun yellAtSafe(person: Person) { println((person.name ?: "Anyone").uppercase() + "!!!") } // Person(null) makes the first function fail at the usage site; // the second prints ANYONE!!!.
Work with platform types by making the nullability decision explicit in your usage:
- Treat the value as non-null and use it directly when its contract guarantees a value; otherwise, a NullPointerException can occur at the usage site. section 7.12.1
- Treat the value as nullable with a null comparison, safe call, or Elvis operator when the Java API may return null. section 7.12.1
- Check Java documentation or implementation because many libraries lack annotations; treating every result as non-null can introduce errors. section 7.12.1
- Choose nullability and mutability separately for Java collection types, including whether the collection and its elements may be null. section 8.2.4
Figure 7.10 Java types without special annotations are represented in Kotlin as platform types. You can choose to use them either as nullable or non-nullable types.
Use the figure to compare unannotated Java types with Kotlin's two permitted interpretations: nullable and non-nullable. section 7.12.1
