https://kotlinlang.org logo
#announcements
Title
# announcements
w

william

06/04/2020, 6:04 PM
Hi kotlin peeps, I'm getting stuck on some java kotlin interop. I have some android code (in java) that I am interacting with that simplifies to this:
Copy code
public class FooService {
    public void addFoo(Foo foo) {
        // woop
    }

    public void removeFoo(Foo foo) {
        // womp
    }
}
interface Foo {
    void callback();
}
and then in the kotlin code I have:
Copy code
class FooKotlin {
    fun buzz() {
        val fooService = FooService()
        fooService.addFoo {
            // do some callback stuff

            fooService.removeFoo(???)
        }
    }
}
I'm not sure what to replace the
???
with in order to remove the callback listener after it has executed once
z

Zach Klippenstein (he/him) [MOD]

06/04/2020, 6:05 PM
you need to store your lambda in a val instead of passing it directly to
addFoo
.
probably something like
Copy code
val fooCallback = Foo { … }
fooService.addFoo(fooCallback)
w

william

06/04/2020, 6:06 PM
@Zach Klippenstein (he/him) [MOD] hey zach! i think i met you at a kotlin SF meetup once upon a time. but anyway i don't think that solves the problem of being able to remove it from within the lambda?
👋 1
z

Zach Klippenstein (he/him) [MOD]

06/04/2020, 6:08 PM
oh, sorry – you’d need to make a
var
and initialize it after declaring it
w

william

06/04/2020, 6:10 PM
Can i do better than making it nullable?
Copy code
fun buzz() {
        val fooService = FooService()
        
        var fooAction: Foo? = null
        fooAction = Foo {
            fooService.removeFoo(fooAction)
        }

        fooService.addFoo(fooAction)
    }
I suppose i could initialize it with an empty lambda but that also seems weird
z

Zach Klippenstein (he/him) [MOD]

06/04/2020, 6:40 PM
i forget if you can use
lateinit
for local vars
👍 1