If you need to handle it inside the function differently, then it is straightforward:

(args.getOrNull(0) ?: error("Missing arg"))
.toIntOrNull() ?: error("Expected int"))

However, if you need to represent this variety of errors in the result of the function, then null is clearly not enough. You’ll need a different approach. Fortunately, this need to represent more details in the result happens exceedingly rare in practice. A single bit of information (result/no result) is enough for most simple functions (and we do strive to keep our functions simple) and the null reference as “no result” indicator is perfect fit to represent it.

Written by

Project Lead for the Kotlin Programming Language @JetBrains

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store