What should firstname be set to if the if branch is not taken?
You’d have to supply a default value. And if you’re doing that, you might as well put the whole declaration outside the if:
var firstname = "default"
if (username != null) {
firstname = username
println(firstname)
}
The only downside to that is that you have to make it a var so you can override that value inside the if. The alternative would be to declare it as val outside the ifwithout an initial value, and add an else branch that would set it:
val firstname: String
if (username != null) {
firstname = username
println(firstname)
} else
firstname = "default"
(As long as the compiler can see that the value always gets initialised, the initialiser doesn’t have to be in the declaration.)