place-wide
place-wide

Reputation: 39

How do you pass an anonymous lambda as an argument in Kotlin?

I'm stuck on how to pass an anonymous lambda as an argument as in the example below:

fun fn_x(x: Int, fn: (Int) -> Int ):Int {
        return fn(x)
}

@Test
{
    assertEquals(3, fn_x(2, ???))
}

In place of "???" I tried:

n->n+1

(n)->n+1

{n -> n+1}

Upvotes: 1

Views: 338

Answers (1)

place-wide
place-wide

Reputation: 39

Ooops. that was a typo. This works

fun fn_x(x: Int, fn: (Int) -> Int ):Int {
    return fn(x)
}

@Test
fun test1()
{
    assertEquals(3, fn_x(2, {n -> n+1}))
}

Upvotes: 1

Related Questions