michpohl
michpohl

Reputation: 1115

Kotlin: Higher order functions, how to add functions to a set and call them

I have a class that holds a set of functions ("listeners") that are supposed to get invoked on a certain event (Gps update on Android, but that shouldn't be important here). It looks like this (vastly simplified for clarity):

class myClass {
private var listeners = mutableSetOf<(Location) -> Unit>()

fun addListener(listener: (Location) -> Unit) {
    listeners.add { listener }
}

private fun updateListeners(location: Location) {
    if (!listeners.isEmpty()) {
        listeners.forEach {
            it.invoke(location)
        }
    }
}

Now I'm trying to add a function to my set from another class that I want to get invoked when updateListeners() is called.

class myOtherClass {

private fun registerLocationListener() {
    myClass.addListener (this::onLocationUpdateReceived)
}

private fun onLocationUpdateReceived(location: Location) {
    // do something with the location data
}

The compiler gives me no warning here, so I first assumed this is right. But onLocationUpdateReceived does not get called. If I log the items in my set with .toString(), I get

Function1<android.location.Location, kotlin.Unit>

which seems to be what I want - but I have limited experience with this matter, so I might be wrong. So I know that updateListeners() gets called, I know that "something" is put into my set, but onLocationUpdateReceived never gets called.

Can anybody help me with how I have to set this up so it works?

Upvotes: 1

Views: 769

Answers (1)

Eugene Petrenko
Eugene Petrenko

Reputation: 4992

There is the bug in the code

fun addListener(listener: (Location) -> Unit) {
    listeners.add { listener }
}

Here you add a new lambda to the listeners collection. The lambda does nothing, as you do not invoke the listener. The right code is

fun addListener(listener: (Location) -> Unit) {
    listeners.add(listener)
}

Or you may say add { listener() }, but I see no reason for that

Upvotes: 6

Related Questions