Kotlin’s Standard functions refer to the functions defined in the standard.kt file, and any kotlin code is free to call all Standard functions.
The with function takes two arguments: the first argument can be an object of any type, and the second argument a Lambda expression. The with function provides the context for the first argument object in the Lambda expression and returns the last line of code in the Lambda expression as the return value. Here’s an example:
Fun fruitListWith(){// Use With to build a string to eat fruit, Val list = listOf("Apple","Banana","Orange","Pear","Grape") val result= with(StringBuilder()){append("Start ") eating fruit.\n") for (fruit in list){ append(fruit).append("\n") } append("Ate all fruits.") toString() } println(result) }Copy the code
Printed logs:
The use and scenario of the run function is very similar to that of the with function, with a few syntax changes. First, the run function is usually not called directly, but is called on an object basis. Second, the run function takes only a Lambda argument and provides the context for the calling object in the Lambda expression. The following is an example:
Fun fruitListRun(){// use run to build a string to eat fruit, Val list = listOf("Apple","Banana","Orange","Pear","Grape") val result= StringBuilder().run{append("Start ") eating fruit.\n") for (fruit in list){ append(fruit).append("\n") } append("Ate all fruits.") toString() } println(result) }Copy the code
The apply and run functions are very similar in that they are called on an object and take only a Lambda argument. The context of the calling object is also provided in the Lambda expression, but the apply function cannot specify a return value. Instead, the calling object itself is automatically returned.
Fun fruitListApply(){// Use apply to build the string to eat the fruit, Val list = listOf("Apple","Banana","Orange","Pear","Grape") val result= StringBuilder().apply{append("Start ") eating fruit.\n") for (fruit in list){ append(fruit).append("\n") } append("Ate all fruits.") // toString() } println(result.toString()) }Copy the code
We’ve gone through some of the most common standard functions in Kotlin, and you’ll see that the uses and scenarios for the with, run, and apply functions are very similar. In most cases, they can be interchangeable, but it’s best to learn the difference so you can make the best choice when programming.