Why won't this compile? ``` val numberOfDoorsI...
# getting-started
b
Why won't this compile?
Copy code
val numberOfDoorsIndex = args.indexOf("--numberOfDoors")
    val numberOfDoors: Int
    if (numberOfDoorsIndex > 0 && args.size > numberOfDoorsIndex) {
        val userSetNumberOfDoorsString = args[numberOfDoorsIndex]
        try {
            numberOfDoors = max(3, abs(userSetNumberOfDoorsString.toInt()))
        }
        catch (ex: NumberFormatException) {
            numberOfDoors = 3 // error here
        }
    }
error:
Copy code
Error:(22, 13) Kotlin: Val cannot be reassigned
Obviously it isn't going to be; if the
NumberFormatException
is thrown, it was never assigned in the first place!
youtrack 1
k
Firstly making a variable val means yoh cannot modify the value and it needs to be initialized although you can use lateInit Try using var
r
I guess the compiler can't tell if the assignment in the
try
block would happen before or after the exception is thrown. In any event, maybe try using
if
and
try
as expressions, ie
Copy code
val numberOfDoors = if (numberOfDoorsIndex > 0 && args.size > numberOfDoorsIndex) {
    val userSetNumberOfDoorsString = args[numberOfDoorsIndex]
    try {
        max(3, abs(userSetNumberOfDoorsString.toInt()))
    }
    catch (ex: NumberFormatException) {            
        3
    }
}
1
r
Oh yeah that's still a very similar issue. Guess it probably is best to just go with
var
k
maybe or could implement the newer approach
m
Try-catch is an expression though, so you could just do
numberOfDoors = try { ... } catch (ex: NumberFormatException) { ... }