Unresolved reference

How can I use the firstname variable outside of the “if” braces?

fun main(args: Array<String>) {
	val username: String? = "ciao"
    if(username != null){
    	val firstname= username
    	println(firstname)
    }
    val nome: String = firstname
}
  • Warning:(12, 8) Variable ‘nome’ is never used

  • Error:(12, 23) Unresolved reference: firstname

Either put the nome declaration inside the if or use username instead of firstname

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