Nullable References
null is a smell in Java that we can’t avoid all the time. If a function that returns an object doesn’t have anything to return at times, then the solution in Java is to return null. This unfortunately leads to an accidental NullPointerException if the caller of the function doesn’t—that is, forgets to—perform an explicit null check. In more recent versions of Java, Optional is used as a solution to this issue, but this approach has three disadvantages. First, the programmer has to use Optional and the compiler won’t force that. Second, Optional involves a small overhead to wrap the object’s reference, or an empty null reference, when there’s no object. Third, a programmer may still return null instead of an instance of
Get Programming Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.