So these are the definitions of the 5 kotlin scopi...
# announcements
n
So these are the definitions of the 5 kotlin scoping functions
Copy code
inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    return receiver.block()
}
inline fun <T> T.also(block: (T) -> Unit): T {
    block(this)
    return this
}
inline fun <T> T.apply(block: T.() -> Unit): T {
    block()
    return this
}
inline fun <T, R> T.let(block: (T) -> R): R {
    return block(this)
}
inline fun <T, R> T.run(block: T.() -> R): R {
    return block()
}
What does the
T.() -> R
imply? I know
(T) -> R
is a function that takes a
T
and returns an
R
, but what does
T.()
mean?
👍 1
l
It means you'll pass an extension function
👍 1
a
l
It will be accessible with
this
s
literally explained,
T.() -> R
refers to a function that can be treated as a member of
T
(and thus has
this
defined in its scope as type
T
), takes no arguments, and returns
R
👍 1
n
excellent info, thank you all! 😄
d
@Nezteb you've come across one of the hardest (IMHO) to grok concepts from the core language, but it is very useful once you get used to it. For the scoping functions, we teach people to just concentrate on using let() and also() initially, and then more into run/apply/with later.
🙏 1
Remember : let == transformation, also = side effects
s
@Nezteb Here's my take on these functions... “Let’s also apply a run with Kotlin on our minds” by Anton Spaans https://medium.com/the-kotlin-chronicle/lets-also-apply-a-run-with-kotlin-on-our-minds-56f12eaef5e3
a
Its a reciever, you guarentee the compiler that the lambda will execute on that T object, and hence the lambda has access to all the functions of that object T.