In contrast to Java, Kotlin enables users to specify whether a variable or function can hold or return null as a value. This can be done as follows:
fun getStringLength(csv: Any): Int? {
noOfTimesMethodsInvoked++;
if (csv is String) {
return csv.length;
}
return null;
}
The getStringLength function returns an Int ending with ?, which specifies that this method should return null. So, the caller of this method must write code to check for null safety. This will be enforced during compile time to reduce the chances of NullPointerException.