Kotlin Programming 2022 Spring - Lecture 5
===
###### tags: `Kotlin 2022 Spring` `Kotlin` `2022 Spring`
Roughly cover the materials in Chapter 9.
## Scope Functions
### [`apply`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html)
```kotlin
import java.io.File
fun main() {
val readOnlyDir = File("readonly")
readOnlyDir.mkdir()
readOnlyDir.setReadable(true)
readOnlyDir.setWritable(false)
readOnlyDir.setExecutable(false)
}
```
is equivalent to
```kotlin
import java.io.File
fun main() {
val readOnlyDir = File("readonly").apply {
// this === File("readonly")
mkdir() // this.mkdir()
setReadable(true)
setWritable(false)
setExecutable(false)
}
}
```
+ `apply` returns the "receiver"
+ `File("readonly")`
### [`let`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html)
```kotlin
fun main() {
val inputLine = readLine()!!
val inputIntSquare = inputLine.toInt() * inputLine.toInt()
println("The square of input is $inputIntSquare.")
}
```
is can be replaced by
```kotlin
fun main() {
val inputLine = readLine()!!
val inputIntSquare = inputLine.toInt().let{
// it === inputLine.toInt()
it * it
}
println("The square of input is $inputIntSquare.")
}
```
+ `let` returns the return value of the anonymous function.
### [`run`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html)
```kotlin
fun main() {
val score = readLine()?.toIntOrNull() ?: 0
val status = run {
if (score >= 60) "P" else "F"
}
println("Score: $score, $status.")
}
```
+ `run` returns the return value of the anonymous function.
### [`T.run`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html)
```kotlin
fun main() {
val score = readLine()?.toIntOrNull() ?: 0
val status = score.run {
// this === score
if (this >= 60) "P" else "F"
}
println("Score: $score, $status.")
}
```
+ Like `apply` but returns the result of the anonymous function.
+ Like `let` but use `this` rather than `it`.
```kotlin
fun main() {
val inputLine = readLine()!!
val inputIntSquare = inputLine.toInt().run{
// this === inputLine.toInt()
this * this
}
println("The square of input is $inputIntSquare.")
}
```
### `with`
```kotlin
fun main() {
val score = readLine()?.toIntOrNull() ?: 0
// val status = score.run {
val status = with(score) {
// this === score
if (this >= 60) "P" else "F"
}
println("Score: $score, $status.")
}
```
+ Similar to `T.run`
### `also`
+ Like `apply` but uses `it` rather than `this`.
+ Like `let` but returns the "receiver"
+ Special usage: swap
```kotlin
fun main() {
var a = 5
var b = 10
println("Before swap: a=$a, b=$b")
a = b.also {b = a}
println("After swap: a=$a, b=$b")
}
```
### Function Selection
Please refer to the [official document](https://kotlinlang.org/docs/reference/scope-functions.html#function-selection).
### `takeIf` and `takeUnless`
```kotlin
fun main() {
val x = "456".takeIf{it.length % 2 == 1}?.toInt()
val y = "456".takeUnless{it.length % 2 == 1}?.toInt()
println("x is $x, and y is $y.")
}
```