alexpfx
alexpfx

Reputation: 6680

Kotlin - Pass array of functions as argument to function

I have this function that (theoretically) accept an array of functions as argument.

fun execute(afterDay: Long, listeners: Array<(List<String>) -> Unit>)

In the client class I trying to call this execute method and pass functions as parameter:

fun updateMovies(ids: Array<String>){

}

fun getNewIds() {
    GetImdbIds(kodein).execute(daysBack.toEpochDay(), [::updateMovies])
}

But it doesn't compiles.

What I'm doing wrong?

the error:

Error:(29, 59) Kotlin: Type inference failed. Expected type mismatch: inferred type is Array<KFunction1<@ParameterName Array<String>, Unit>> but Array<(List<String>) -> Unit> was expected
Error:(29, 59) Kotlin: Unsupported [Collection literals outside of annotations]

Upvotes: 1

Views: 14117

Answers (1)

Todd
Todd

Reputation: 31700

I got this to work by making two changes.

First, your updateMovies function as written takes an Array<String>, when your listeners wants functions that take List<String>. So, we can make this change:

fun updateMovies(ids: List<String>) {
    TODO()
}

Next, if you create your array of function references using arrayOf() instead of attempting an illegal array literal, this should compile:

GetImdbIds(kodein).execute(1L, arrayOf(::updateMovies))

Upvotes: 5

Related Questions