I'm working on this thing that has some function callings like this:
fun f1(){
// does some stuff
f2();
}
fun f2(){
// does some stuff
f1();
}
This is a simplification of what my code looks like (it doesn't go for an infinity loop). My problem is that it returns the error that f2 is unreferenced. I tried searching this online but the only solutions I saw from people asking where to move the function above the funciton call, but that wouldn't work for me since my other function calls that one as well and moving the f2 above f1 would just make f1 unresolved when f1 is called from f2.
I also tried the function declaration thing c and c has but it lead to errors saying I have ambiguous function definitions and that they're expecting a function body in the function declaration.
Thanks.
CodePudding user response:
I am assuming you are trying to define both functions inside the same local scope and getting an "Unresolved reference" Kotlin compiler error.
If that is your case and you cannot refactor your flow in a better way, then you can declare one of the functions as a nullable variable and assign it later. Your code would then become
var f2: (() -> Unit)? = null
fun f1() {
// does some stuff
// Option 1: wont get invoked if f2 is null when this line is executed
f2?.invoke()
// Option 2: will always try to get invoked, but if f2 is null when this line is executed,
// it will throw a NullPointerException
f2!!.invoke()
}
f2 = {
// does some stuff
f1()
}