https://kotlinlang.org logo
#announcements
Title
# announcements
n

Nezteb

08/06/2019, 6:18 PM
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

LeoColman

08/06/2019, 6:19 PM
It means you'll pass an extension function
👍 1
a

artem_zin

08/06/2019, 6:19 PM
l

LeoColman

08/06/2019, 6:19 PM
It will be accessible with
this
s

Shawn

08/06/2019, 6:23 PM
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

Nezteb

08/06/2019, 6:23 PM
excellent info, thank you all! 😄
d

dave

08/06/2019, 8:10 PM
@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

streetsofboston

08/06/2019, 10:10 PM
@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

Animesh Sahu

08/07/2019, 2:33 AM
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.