Java: In this method, compiler gives error "Variable used in lambda expression should be final or effectively final":
void javaAnonymousClass(Button button) {
String localVar = "10";
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
localVar = "5";
}
});
}
Java: In this method in "Variable 'localVar' is accessed from within inner class, needs to be final or effectively final"
void javaLambda(Button button) {
String localVar = "10";
button.setOnClickListener(v -> System.out.println(localVar));
localVar = "";
}
Kotlin. No error whatsoever.
fun kotlinLambda(button: Button) {
var localVar: String = ""
button.setOnClickListener {
localVar = "5"
}
localVar = "7"
}
My question is: WHY there is no such problem of not being final (val) in Kotlin?