3

Here I read about how closures were managed in Java. As to Kotlin, I expected that a variable had to be effectively final as well (in other words val, not var) to be available in a lambda function.

But the following code snippet works.

var stringBuilder = StringBuilder()
stringBuilder.append("Old")
stringBuilder = StringBuilder()
stringBuilder.append("New")

sample_btn.setOnClickListener {
    Toast.makeText(this, stringBuilder.toString(), Toast.LENGTH_LONG).show()
    // New is shown
}

So stringBuilder doesn't need to be final to be used in the lambda funcation. I wonder what's going on under the hood, and why my code works.

niceman
  • 2,653
  • 29
  • 57
Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138

0 Answers0