Skip to the content.

Functional Style in Kotlin

In general a function has 4 parts

A lambda function only contains the last two.

general syntax for a lambda function in Kotlin

{ parameter -> body }

General Syntax

The range.none

// signature - one argument - a lambda function
none(predicate: (Int) -> Boolean): Boolean

// call to check if any equal numbers is in a range
2..10.none({ i: Int -> i % 2 == 0})

// the parameter type can be dropped
2..10.none({ i -> i % 2 == 0})

// the parenthesis can be dropped as well when the function only takes the lambda function as argument
2..10.none { i -> i % 2 == 0}

// for lambdas that only has one parameter it is explicitly named 'it'
2..10.none { it % 2 == 0}

Function References

When passing through parameters function references can be used

({ x -> someMethod(x) })
// can be written with a function reference
(::someMethod)

// if the pass-through is to another lambda, :: is not needed
1..5.forEach { action(it) }
// can be simplified
1..5.forEach { action }

Internal Iterators

Standard functional operations defined on Iterable

Sequences

The Sequence is a lazy evaluated iterator. This should be preferred when doing iteration on large collections.

A normal array and Iterable can easily be wrapped in a Sequence by using asSequence