Say I have this block of code:
val cmd: CommandLine
try {
cmd = parser.parse(options, args)
} catch (ex: ParseException) {
// do stuff
}
// error: cmd is not initialized
val inputArg = cmd.getOptionValue("someArg")
I get the error because cmd is not initialized which is expected and normally I'd initialize it with a null
value in Java but what if the type is non-null
and I don't want to move all my logics to try
block?
You have a few options.
The first option is to make cmd
a var
and assign it a default value or null. Of course, you'll need to check for null after the try-catch if you make cmd
nullable. (I recommend some kind of default value, maybe an EmptyCommandLine
of some kind).
The second option is to use the try-catch as an expression like so:
val cmd: CommandLine = try {
parser.parse("options", "args")
} catch (ex: Exception) {
// Must:
// 1) Throw, or error in some other way so as to return Nothing.
// 2) Return a default/failed value for cmd. Maybe something like EmptyCommandLine or FailedCommandLine(ex)
// 3) Make cmd nullable and return null.
CommandLine() // or, error("Unable to parse options!")
}
val inputArg = cmd.getOptionValue("someArg")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With