How to declare a function as a variable in Kotlin

Viewed 13566

So I am trying to create a listener in Kotlin. I just want to pass a method that will be executed latter in my code. Like this:

override fun setButtonClickListener(listener: (text: String) -> Unit) {
    this.listener = listener
}

But, when I declare my listener, I must declare it like this:

private var listener : (text: String) -> Unit = null!!

Otherwise my AS will complain. But this !! in a null object seams so weird. How should I declare this listener??

Thanks!

2 Answers

Every time I forget how to do this I end up with this answer, but it's not exactly what I need, so if you are looking for a way to create a function that generates some code into your function it would look like this

val createMock: (String, Int, Int, Boolean) -> MyMockType =
    { language: String, major: Int, minor: Int, published: Boolean ->
        MyMockObject(
            language = language,
            majorVersion = major,
            minorVersion = minor,
            published = published,
            content = "",
            createdAt = Timestamp(12345000)
        )
    }

val englishMock = createMock("en", 1, 0, true)
val portuguesMock = createMock("pt-BR", 1, 0, true)
Related