Zorgan
Zorgan

Reputation: 9173

How to use kotlin function literals?

So I've got a function literal here:

fun task(): List<Boolean> {
    val isEven: Int.() -> Boolean = { this % 2 == 0 }
    val isOdd: Int.() -> Boolean = { this % 2 != 0 }

    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

and I understand exactly how it's working inside the function - but how is it used outside the function? How is task() called? (practical example preferably)

Upvotes: 0

Views: 120

Answers (1)

Sergio
Sergio

Reputation: 30745

When you define function literals inside a function they are available only in the scope of that function:

fun task(): List<Boolean> {
    val isEven: Int.() -> Boolean = { this % 2 == 0 } // unavailable outside the `task` function
    val isOdd: Int.() -> Boolean = { this % 2 != 0 }  // unavailable outside the `task` function

    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

If you want to access those function literals outside the function you need to move them outside the task function:

val isEven: Int.() -> Boolean = { this % 2 == 0 }
val isOdd: Int.() -> Boolean = { this % 2 != 0 }

fun task(): List<Boolean> {
    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

fun anotherTask(): List<Boolean> {
    return listOf(2.isOdd(), 23.isOdd(), 2948.isEven())
}

OR

Instead of using function literals you can create extension functions:

fun Int.isEven(): Boolean { return this % 2 == 0 }
fun Int.isOdd(): Boolean { return this % 2 != 0 }

fun task(): List<Boolean> {
    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

fun anotehrTtask(): List<Boolean> {
    return listOf(2.isOdd(), 23.isOdd(), 2948.isEven())
}

Upvotes: 3

Related Questions