天天看點

【Kotlin】this還是it?合理使用with操作符使用with優化代碼平衡性很重要合理使用Kotlin

【Kotlin】this還是it?合理使用with操作符使用with優化代碼平衡性很重要合理使用Kotlin

使用with優化代碼

在這裡插入代碼片

下面是一段常見的UI配置邏輯:

applicationWindow.title = "Just an example"
applicationWindow.position = FramePosition.AUTO
applicationWindow.content = createContent()
applicationWindow.show()
           

applicationWindow

需要反複調用,此時我們可以

with

進行優化,使代碼更加簡潔易讀

with(applicationWindow) { // this: ApplicationWindow
    title = "Just an example"
    position = FramePosition.AUTO
    content = createContent()
    show()
}
           

with(..){...}

本質上是對帶有receiver的擴充函數的封裝

fun <T, R> with(receiver: T, block: T.() -> R): R =
    receiver.block()
           

既然

with

這麼棒,為什麼不更多地使用呢?

Kotlin中源碼中充滿對帶有receiver的擴充函數的應用,例如filter

使用時:

此處的

it

,可以很好地提示給開發者

persons

的屬性是

firstName

而非

name

如果我們定義成

predicate: T.() -> Boolean

,使用時:

可讀性就有

it.firstName

那麼好了。

平衡性很重要

The key quality of the code that we are looking to achieve is not concision, but readability

代碼的可讀性相對于簡潔更重要

代碼過長容易導緻無謂的重複;代碼過于精簡又會隐含了大量的上下文,增加了解成本。所謂好的代碼需要在可讀性和簡潔性中做一個tradeoff。

合理使用Kotlin

Kotlin提供了靈活的文法特性,可以寫出相對于Java更加簡潔的代碼。但我們也要注意避免“矯枉過正”、一味追求代碼簡潔因而影響了可讀性。另外,除了

with

以外,其他的作用域函數例如

apply

also

也都有他們适合的場景,明确他們的含義,将

it

this

應用到最合适的場景中才能寫出漂亮的代碼。