Summary of the Usage and Difference of Built in Functions in Kotlin

  • 2021-09-11 21:21:30
  • OfStack

Preface

In the source standard library in Kotlin (Standard. kt), a number of built-in functions extended by Kotlin are provided to optimize the coding of kotlin. Standard. kt is part of the Kotlin library, which defines a number of basic functions. Although this source code file has less than 50 lines of code, these functions are very powerful.

This article mainly records kotlin let, apply, run, also, with and other functions of the usage and differences, the following words do not say much, to see a detailed introduction

0. let


val a = "hello,kotlin".let{
 println(it)
 3
}

println(a)

hello,kotlin
3

Definition:


public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

Explanation: The let function of "hello, kotlin" is called, it replaces the object in scope (hello, kotlin), and the last line of the function is returned by default

1. apply


val a = "hello,kotlin".apply{
 println(this)
}

println(a) 

hello,kotlin
hello,kotlin

Definition:


public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

Explanation: The object that calls the apply function can be replaced by this in the function, and the return value is the object itself.

2. run


val a = "hello,kotlin".run{
 println(this)
 2
}

println(a) 

hello,kotlin
2

Definition:


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

Explanation: According to the above execution code, the run function returns the last line within the closure.

3. also


val a = "hello,kotlin".also{
 println(it)
}

println(a) 

hello,kotlin
hello,kotlin 

Definition:


public inline fun <T> T.also(block: (T) -> Unit): T {
 block(this)
 return this
}

Explanation: As you can see from the source code definition, also executes block (closure) and returns this, the object that calls the also function.

4. with


val a = with("string") {
 println(this)
 3
}
println(a)

string
3

Definition:


public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

Explanation: It is not an extension function. It takes the specified object as the parameter of the function, replaces the object in scope this, and returns the last line of the object. The specified T is the receiver of the closure, using the return result of the closure in the parameter.

Above, pay attention to reading the source code of Kotlin related high-order functions. If the last parameter in the function is a closure, then the last parameter can be written behind the parentheses instead of in parentheses. If there is only one parameter, the parentheses can also be removed.

Summarize


Related articles: