Using a flag to switch between two methods

Hey guys

a quick question about the language, I feel like this is something I do quite frequently:

if(condition) is:true then call 'add' else is:false then call 'remove'

I think we can generalize add to ‘someForwardMethod’ and remove to ‘someReverseMethod’. Often we derrive whether we want to go forward or backward from some domain logic, in that sense we need to map from a boolean value to a functor.

java eg:

implicitTerminalStyle.addListener((source, wasImplicit, isNowImplicit) -> {
  if(isNowImplicit == wasImplicit){ return; }

  if(isNowImplicit){
    getSemanticListeners().add(listener);
  }
  else{
    getSemanticListeners().remove(listener);
  }
});

with kotlin, and with respect to the body, I’m wondering if I can get some first-class-coolness on add and remove to refactor this out, I was hoping for

semanticListeners.run { if(isNowImplicit) ::add else ::remove } (listener)

but my types are getting all confused.

The closest I’ve been able to get is

semanticListeners.run{ if(isNowImplicit) { x:String -> add(x) } else { x:String -> remove(x) }}("Something")

Is there something I can do to leverage better type inference here or is this just too much inference for kotlin (or for kotlin 1.0, but not 1.1?)

Thanks for any help!

1 Like

This should work.

 getSemanticListeners().run { if(isNowImplicit) add(listener) else remove(listener) }

Trying to use references to the methods will probably work better in 1.1