0

I am trying to change the location of an image, and to do that I need a certain variable, which I initialized at the start of this code. I am able to call the variable multiple times with no problem, expect for the second time I call it, on line 7. The exact error is "Variable 'currentHall' must be initialized." How can I fix this?

var currentHall: Hall

for (i in 0..11) {
    if(halls[i].name == locationHall) {
        currentHall = halls[i]
    }
}

if (currentHall.image == "segment_hori.png") {
    youAreHere.y = currentHall.yCoord
    youAreHere.x = currentHall.xCoord + locationCoords
}

if (currentHall.image == "segment_vert.png") {
    youAreHere.y = currentHall.yCoord + locationCoords
    youAreHere.x = currentHall.xCoord
}
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
Chadcock
  • 5
  • 3
  • What do you expect `currentHall` to be if the `if` condition inside the loop never evaluates to true? – UnholySheep May 30 '22 at 22:30
  • There is no case where it could not be true, all that is doing is checking which Hall object is the one that should be used based on an input. – Chadcock May 30 '22 at 22:37
  • 5
    That is knowledge that you have, but the compiler doesn't. All it sees is the code and given that code it would be possible that `currentHall` never gets assigned a value. You can try to "convince" the compiler by e.g.: marking the variable as `lateinit` – UnholySheep May 30 '22 at 22:43
  • Setting it as lateinit worked, thank you – Chadcock May 30 '22 at 22:44
  • 1
    Does this answer your question? [How to create variable in Kotlin without initialization?](https://stackoverflow.com/questions/52964417/how-to-create-variable-in-kotlin-without-initialization) – Martin Zeitler May 30 '22 at 23:04

0 Answers0