Passing reference to function

I’m having something “observable” like this:

class SomethingObservable {

   public fun onSomething(listener: (event: Event) -> Unit) {
      // adds listener 
   }

   public fun unSomething(listener: (event: Event) -> Unit) {
      // removes listener 
   }
}

And I would like to pass a class member function as the function reference like this:

class SomeoneObserving {
  
     val somethingObservable: SomethingObservable
    
     fun startObserving() {
        somethingObservable.onSomething(::handleEvent)
     }

     fun stopObserving() {
        somethingObservable.unSomething(::handleEvent)
     }

     private fun handleEvent(event: Event) {
          ...
     }
}

But instead I get the compilation errors:

  • Type mismatch: inferred type is kotlin.reflect.KFunction2<SomeoneObserving, Event, kotlin.Unit> but (Event) -> kotlin.Unit was expected
  • Left-hand side of a callable reference with a receiver parameter cannot be empty. Please specify the type of the receiver before '::' explicitly

Does anyone know how to accomplish this?

Thanks!

Jørund

As far as I know, function references are currently quite limited, and you’ll have to use somethingObservable.onSomething { handleEvent(it) } for now.

Better not to pass listener as { handleEvent(it) } if you want to unsubscribe that listener later. The point is that each lambda expression corresponds to its own instance of the function (event: Event) -> Unit.

It would be better for now to store the function in a property, and pass value of that property as listener:

class SomeoneObserving {
  
     val somethingObservable: SomethingObservable
    
     fun startObserving() {
        somethingObservable.onSomething(handleEvent)
     }

     fun stopObserving() {
        somethingObservable.unSomething(handleEvent)
     }

     private val handleEvent = { event: Event ->
          ...
     }
}
1 Like