Use with to optimize code
在这里插入代码片
The following is a common UI configuration logic:
applicationWindow.title = "Just an example"
applicationWindow.position = FramePosition.AUTO
applicationWindow.content = createContent()
applicationWindow.show()
applicationWindow
Need to call repeatedly, at this time we can with
optimize to make the code more concise and easy to read
with(applicationWindow) {
// this: ApplicationWindow
title = "Just an example"
position = FramePosition.AUTO
content = createContent()
show()
}
with(..){...}
Essentially, it is an encapsulation of the extension function with the receiver
fun <T, R> with(receiver: T, block: T.() -> R): R =
receiver.block()
Since it's with
so great, why not use it more?
The source code in Kotlin is full of applications of extension functions with receivers, such as filters
fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T>
when using it:
persons.filter {
it.firstName == name }
Here it
, persons
the attribute that can be a good reminder to the developer is firstName
not name
,
If we define it as predicate: T.() -> Boolean
:
persons.filter {
firstName == name }
The readability is it.firstName
so good.
Balance is important
The key quality of the code that we are looking to achieve is not concision, but
readability
Too long code can easily lead to unnecessary repetition; too simple code will imply a lot of context and increase the cost of understanding. The so-called good code requires a tradeoff in readability and conciseness.
Use Kotlin reasonably
Kotlin provides flexible syntax features and can write more concise code than Java. But we must also pay attention to avoiding "overcorrection" and blindly pursuing code conciseness which affects readability. In addition, in addition to with
other scope functions, for example apply
, also
they also have their suitable scenarios. Clear their meanings it
and this
apply them to the most suitable scenarios to write beautiful code.