Consider the following Kotlin code calling a Java method that returns a platform type. What will be the output?
fun main() { val javaString: String = getJavaString() println(javaString.length) } // Java method signature: public static String getJavaString() { return null; }
Platform types can be null but Kotlin does not enforce null checks on them.
The Java method returns null, but Kotlin treats the return as a platform type (String!). Accessing length without a null check causes a NullPointerException at runtime.
Which statement best describes platform types in Kotlin when calling Java code?
Think about how Kotlin handles nullability when it cannot be sure from Java.
Platform types represent types coming from Java where Kotlin cannot be sure if they are nullable or not. Kotlin allows using them as nullable or non-nullable but warns about potential null issues.
Given this Kotlin code calling a Java method, why does it throw a NullPointerException?
val result: String = getJavaString() println(result.length)
Java method getJavaString() returns null.
Consider how Kotlin interprets Java types without nullability annotations.
Kotlin treats Java types without nullability annotations as platform types, which it assumes to be non-nullable unless checked. Since the Java method returns null, accessing length causes a NullPointerException.
Which Kotlin declaration correctly handles a platform type from Java that might be null?
Think about how to safely handle possible null values from Java.
Declaring the variable as nullable (String?) allows Kotlin to safely handle null values from platform types. The other options are either invalid syntax or unsafe.
You have a Java method String getUserName() that may return null. How should you safely use it in Kotlin to avoid runtime exceptions?
Consider Kotlin's null safety operators to provide a default value.
Using the Elvis operator ?: provides a default string if getUserName() returns null, preventing NullPointerException. Option D forces a null check that can crash, A accesses length on nullable without safe call, and D assumes non-null.