使用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
fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>
使用时:
persons.filter {
it.firstName == name }
此处的it
,可以很好地提示给开发者persons
的属性是firstName
而非name
,
如果我们定义成predicate: T.() -> Boolean
,使用时:
persons.filter {
firstName == name }
可读性就有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
应用到最合适的场景中才能写出漂亮的代码。