Zorgan
Zorgan

Reputation: 9123

Why do Kotlin/Java functions look so different in real use from documentation?

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

Answers (2)

Ge3ng
Ge3ng

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

zsmb13
zsmb13

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----|
  1. This function is inline. This means that its body essentially gets copy-pasted to the call site at compile time, as an optimization measure (used in this case because it has a lambda parameter).
  2. Declares a function.
  3. Type parameter list, this function has one generic type parameter called T.
  4. This is an extension function, and this is its receiver, i.e. the type being extended. This function will be callable on any 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.
  5. The name of the function.
  6. The name of the first and only parameter of the function (if we don't count the receiver, which is technically also a parameter).
  7. The type of the function's parameter. This is a function type, which describes a function that takes a single 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.
  8. The return type of the function.

Upvotes: 5

Related Questions