Lazy initialization lateInit, lazy

Lateinit and lazy are two ways to implement lazy initialization in Kotlin.

  • Lateinit can only be used for variables labeled with var, and by lazy can only be used for variables labeled with val.
  • By lazy is initialized only on the first call.
class User {
    private lateinit var name: String
    private val password: String by lazy {
        println("lazy init")
        "admin"
    }

    fun setName(name: String) {
        this.name = name
    }

    fun show(a) {
        println("name = $name")
        println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --")
        println("First access password =$password")
        println("Second access password =$password")}}fun main(a) {
    val user = User()
    user.setName("tomcat")
    user.show()
}
Copy the code

Output result:

Name = tomcat -------------------- lazy init First access password = admin Second access password = adminCopy the code

Commissioned by

/** * defines the Base interface ** /
interface Base {
    fun say(a)
}

/** * Define the Base interface implementation class and implement the say() method */
class BaseImpl : Base {
    override fun say(a) {
        println("BaseImpl say()")}}/** * the BaseProxy class implements the Base interface by delegating all the methods in the Base interface to the Base object. * Simplifies the methods to implement when implementing an interface. * /
class BaseProxy(base: Base) : Base by base

fun main(a) {
    val baseImpl = BaseImpl()
    The BaseImpl say() method is called
    BaseProxy(baseImpl).say()
}

Copy the code

Output result:

BaseImpl say()
Copy the code

Extension function

Extension functions can add additional member functions to a class by “class name”. Method name “method.

/** * define the extension function to add the readText() method to File */
fun File.readText(charset: Charset): String = readBytes().toString(charset)

/ / call
fun main(a) {
    val file = File("/Users/xing/Desktop/Android.md")
    print(file.readText(Charset.forName("utf-8")))}Copy the code

Lambda closure

Lambda expressions are essentially anonymous functions, and their underlying implementation is implemented through anonymous functions.

Features:

  • Lambda expressions are always enclosed in braces;

  • Its arguments, if present, are declared before ->;

  • The function body (if present) is written after ->;

  • If Lambda is the last argument to a function, you can put curly braces outside the function parentheses.

  • If the function has only one argument and the argument is Lambda, the parentheses can be omitted.