Reputation: 9123
For example here is all()
in action:
fun Shop.checkAllCustomersAreFrom(city: City): Boolean =
customers.all { it.city == city }
And here is the equivalent from the kotlin documentation:
inline fun <T> Iterable<T>.all(
predicate: (T) -> Boolean
): Boolean
Can someone please explain each part of the second code block and why it's written like that?
Apologies if this is a basic question, but if I learn this it will be much easier to read documentation.
Upvotes: 0
Views: 72
Reputation: 2430
inline - Take the body of this function and put it where it is being called when compiled instead of calling a function.
fun - function declaration
- generic type called T
Iterable - class we are adding an extension function too. (If it is not inline
read static function)
all - name of the function
predicate - parameter named predicate
: (T) -> Boolean - Lambda Type takes a T as a parameter and returns a Boolean. Usually in the form { it == foo }
: Boolean - Returns a Boolean
Upvotes: 1
Reputation: 89578
Let's break it down, shall we?
inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean
|--1--|-2-|-3-|-----4-----|-5-|----6-----|------7-------|----8----|
T
.Iterable<T>
as if it was a member function. The Iterable
that it was called on can be accessed inside the function's body as this
.T
parameter, and returns a Boolean
. This can be a reference to a regular function that has this signature, but the expectation with collection functions such as this is that most of the time this will be a lambda.Upvotes: 5