Hi! When I have ```class Builder { fun withSome...
# intellij
d
Hi! When I have
Copy code
class Builder {
  fun withSomeAction(action: (P) -> Unit)
}
and autocomplete this on usage site, IDE turns this into
Copy code
Builder().withSomeAction { }
which sometimes leads to programmer errors when actions are an object. Instead I'd like to have
Copy code
Builder().withSomeAction(action)
Is there a way to give IDE a hint I don't want to expand here? I recall there was some YouTrack issue about this, but I can't find it.
r
I played around a bit with this, and you could use SAM interfaces:
Copy code
fun interface Action {
    fun doAction(x: Int)
}

class Builder {
    fun withSomeAction(action: Action): Builder { return this }
}
then you could use em like this
Copy code
val action1 = Action { TODO() }
object Action2 : Action by (Action { TODO() })
object Action3 : Action {
    override fun doAction(x: Int) = TODO()
}

Builder()
    .withSomeAction(action1)
    .withSomeAction(Action2)
    .withSomeAction(Action3)
    .withSomeAction { println(it) }
and IntelliJ will default to filling
.withSomeAction(|)
instead of using
.withSomeAction { | }
depends on what exactly you are doing, if you want to use mostly pre-defined actions, this could be great way of doing that
actually even smth like this would work, (with changes of
override fun doAction
->
override fun invoke
Copy code
fun interface Action : (Int) -> Unit
but it's a tiiny bit of abuse 😛 Point is, when IntelliJ sees interface there as argument, it won't autofill lambda, but since it's a functional interface, you can still use lambas normally, and bonus, you have name for the type your objects implement
d
Nice! Thank you for these tips!