# Listener Idiom

**URL:** <https://discuss.kotlinlang.org/t/listener-idiom/1858>\
**Category:** Language Design\
**Created:** [July 10, 2016, 2:55pm UTC](https://discuss.kotlinlang.org/t/listener-idiom/1858 "2016-07-10T14:55:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tmarsteel1](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/tmarsteel1/32/2042_2.png) [@tmarsteel1](https://discuss.kotlinlang.org/u/tmarsteel1)\
**Post date:** [July 10, 2016, 2:55pm UTC](https://discuss.kotlinlang.org/t/listener-idiom/1858/1 "2016-07-10T14:55:46Z")

</div>

I wonder if there is a preferred idiom on event listeners in Kotlin. My initial thought was: listeners with more than one method are pointless in Kotlin since lambdas cannot be used with them. As a result, i’d create all my listener interfaces like this:

```
interface FooListener {
    /**
     * Called when the foo event occurs.
     */
    public fun onFoo()
}

```

But Kotlin has these nice function types that render seperate interface declarations extremely verbose (especially when there are 5 interfaces because each interface is a SAM, e.g. `MouseListener`). In consequence, the listeners can be declared as functions:

```
class X {
    private val MutableList<() -> Unit> fooListeners = mutableListOf()

    public fun onFoo(listener: () -> Unit) = fooListeners.add(listener);

    public fun foo() {
        /* code ... */
        fooListeners.forEach{ it() }
    }
}

```

That version does not allow a doc-comment on the listener method. But that can be really important, especially when having to point out under what conditions a listener is invoked, to explain parameter ranges etc…

My questions are:

- Ist there any idiom for this in Kotlin? How are true-Kotlin events+listeners to be implemented?
- Can a function type be aliased (for the purpose of the doc comment)? And would that be any better than declaring an interface per event?

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [July 11, 2016, 9:11am UTC](https://discuss.kotlinlang.org/t/listener-idiom/1858/2 "2016-07-11T09:11:46Z")

</div>

I think that using a list of elements of a function type is the most idiomatic solution for 1.0. Kotlin 1.1 will support type aliases, so you’ll be able to use them for the listeners.
