0

I'm new to kotlin and I don't know English well so "Google Translate hello!". I want to return the values that I received during the execution of the if condition. This function iterates through the columns in the excel table until it finds the one I need and returns its number

I tried to write return@getTableValue to indicate where to return the value, but it didn't give anything, I don't understand, help

My code:

private fun getTableValue(xlWs: Sheet, groupe: String, dopgroupe: String): Int { var gr: String var cellNumb: Int var res: Int for (i in 0..20){ gr = xlWs.getRow(0).getCell(i).toString() if (gr == groupe){ cellNumb = i if (dopgroupe == "1") { res = cellNumb } if (dopgroupe == "2") { res = cellNumb + 2 } } } return res // Error Variable 'res' must be initialized } 
1
  • You should assign val in all path. If you are sure it will get a value, you can use lateinit var instead. Commented Jan 8, 2023 at 8:18

1 Answer 1

0

You only set res inside if statements, so the compiler cannot be sure that you ever set a value to res. You can only use a variable’s value after it is guaranteed to have been set to something. In this case, the easiest solution is to give the variable an initial value at the declaration site, like this:

var res: Int = 0 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I thought that he does not see changes in other operators, so I thought that if I give the initial value, he will only display it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.