The use of .() of Kotlin higher-order functions

Below I give a total of three examples, the first of which is to use .() for modification, which is the simplest way, the second is that the negative example cannot be compiled, and the third example is not Extend the apply method with .().

1. Let's add a myApply function to StringBuilder and use it normally. Because of the addition of .(), the this keyword can be used in the myApply code block:

//给StringBuilder增加一个myApply,入参位空
//StringBuilder.()     意味着在使用myApply的代码块里可以使用this,this代表调用myApply的对象本身
fun StringBuilder.myApply(block: StringBuilder.() ->Unit) : StringBuilder {
    block()
    return this
}

var sb = StringBuilder("123")
sb.myApply {
    this.append("456")
    this.append("654")
    //如果定义myApply的时候不加.()这里是不可以使用this的
}
println(sb)

//结果:123456654

2. This cannot be used without adding StringBuilder.()

fun StringBuilder.myApply1(block: () ->Unit) : StringBuilder {
        block()
        return this
    }

    var sb1 = StringBuilder("123")
    sb1.myApply1 {
        append("456")//编译不过,因为block的入参没有使用StringBuilder.修饰
        append("654")
    }
    println(sb)

3. If the String.() modification is not applicable, you need to pass in StringBuilder as an input parameter, and then return the parameter.


    fun StringBuilder.myApply1(block: (sb:StringBuilder) ->StringBuilder) : StringBuilder {
        block(sb)
        return sb
    }

    var sb1 = StringBuilder("1234444")
    var sss = sb1.myApply1 {sbParam ->
        sbParam.append("456")
        sbParam.append("654666")
        println("myApply1 code block $sbParam")
        sbParam
    }
    println(sss)

Guess you like

Origin blog.csdn.net/mldxs/article/details/127133133