Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing non-null type variable before try/catch

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?

like image 455
Yar Avatar asked Sep 15 '25 12:09

Yar


1 Answers

You have a few options.

1) You could use var

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).

2) Better yet, use try-catch as an expression

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")
}
like image 84
Aro Avatar answered Sep 18 '25 05:09

Aro