Kotlin之“with”函式和“apply”函式

Troll4it發表於2018-08-26

Fighting.jpg

“with”函式

要想了解"with"函式先來看一段程式碼

  fun alphabet(): String {
        var stringBuilder = StringBuilder()

        for (letter in 'A'..'Z') {
            stringBuilder.append(letter)
        }
        stringBuilder.append("\n Now I know the alphabet!")
        return stringBuilder.toString()
    }

    fun alphabetWith(): String {
        var stringBuilder = StringBuilder()
        return with(stringBuilder) {
            for (letter in 'A'..'Z') {
                this.append(letter)  //this代表stringBuilder
            }
            this.append("\n Now I know the alphabet")
            this.toString()
        }
    }
複製程式碼

執行結果

08-26 15:20:58.516 24082-24082/com.troll4it.kotlindemo I/System.out: alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:20:58.517 24082-24082/com.troll4it.kotlindemo I/System.out:  Now I know the alphabet!
    alphabetWith:ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:20:58.518 24082-24082/com.troll4it.kotlindemo I/System.out:  Now I konw the alphabet
複製程式碼

通過上面程式碼可以看出,執行結果一樣,但是alphabet()是最常規的寫法, alphabetWith()方法則運用了今天的重點講解的函式with()函式

wtih結構看起來像一種特殊的語法結構,但它是一個接收兩個引數的函式:引數分別是stringBuffer和一個lambda
with函式把它的第一個引數轉換成第二個引數傳給它的lambda的接收者,可以顯示地通過this引用來訪問這個接收者,但是上述方法alphabetWith()方法的this是可以省略的。
with返回的值是lambda程式碼的返回值結果

"apply"函式

同時想了解apply函式先看一段程式碼

  fun alphabetApply():String=StringBuffer().apply {
        for (letter in 'A'..'Z') {
         append(letter)
        }
       append("\n Now I know the alphabet")
    }.toString()
複製程式碼

執行結果:


08-26 15:50:48.888 25155-25155/com.troll4it.kotlindemo I/System.out: alphabetApply:ABCDEFGHIJKLMNOPQRSTUVWXYZ
08-26 15:50:48.889 25155-25155/com.troll4it.kotlindemo I/System.out:  Now I konw the alphabet

複製程式碼

apply被宣告成一個擴充套件函式,它的接受者變成作為實參的lambda的接受者。執行apply的結果就是StringBuffer

總結:

  • with返回的值是執行lambda程式碼的結果,該結果是lambda中的最後一個表示式的值。
  • apply返回的值是lambda接受者的物件

後記

摘自《Kotlin實戰》

相關文章