[Cotlin] I'd like to ask you about the expansion function of the Cotlin standard library (also, let, with, apply, etc.)ㅛ

Asked 6 days ago, Updated 6 days ago, 1 views

inline fun <T, R> T.run(block: T.() -> R): R {
    return this.block()

The book says that the run extension function is defined in this way.

The explanation of this is as follows

The block parameter receives a function in the form of T.() -> R and immediately calls the run extension function, this.block() Call and pass the receiver of the run to the function indicated by the block.

In other words, when called as "Hello".run { println(this)}, the run extension function is as follows.

fun String.run(block: String.() -> Unit): Unit {
    // // block = println(this)
    return this.block()

What I don't understand here is... The extended function allows access to the receiver member using this inside the block

If you do it,

But here this.If you do block... I think it means calling the block() member function of the String type.

As far as I know, there is no block function inside the String class.How is this possible?

Shouldn't it just be block() from return

And if the additional question is block is String() -> Unit, shouldn't we receive the extension function of String as a parameter?

println is just println itself. How does this work?

It's very confusing


2022-09-20 15:44

1 Answers

inline fun <T, R> T.run(block: T.() -> R): R {
    return this.block()

For T.() -> R in this code, see Function Types and Function literals with receiver will be quick to understand!

Function literals with receiver can be implicitly expressed as this and has access to members of that receiver object. this can be omitted, so this.Block() and block() can be viewed in the same sense. As you mentioned, there is a property similar to an extension function, but it does not mean an extension function.

Thus, this.Both block() and block() are available, and extended functions cannot be called as parameters.

You can call Function Type as follows :)

valop: String() -> Unit = { println()}

2022-09-20 15:44

If you have any answers or tips

© 2022 pinfo. All rights reserved.