Standard library functions
Kotlin provides a standard library that is meant to augment, not replace, the standard Java library. There are many functions that adapt Java types and methods and allow them to be used as idiomatic Kotlin. In this chapter, we will cover some of the lower level functions that have far reaching use.
Apply
Apply is a Kotlin standard library extension function declared on Any, so it could be invoked on instances of all types. Apply accepts a lambda that is invoked with the receiver being the instance where apply
was called on. Apply then returns the original instance.
It's primary use is to make the code that needs to initialize an instance more readable by allowing functions and properties to be called directly inside the function before returning the value itself. Refer to the following code:
val task = Runnable { println("Running") } Thread(task).apply { setDaemon(true) }.start()
Here we created a task, an instance of Runnable
, and then created...