[Kotlin] This or it? Use the with operator reasonably

Insert picture description here

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()

applicationWindowNeed to call repeatedly, at this time we can withoptimize 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 withso 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, personsthe attribute that can be a good reminder to the developer is firstNamenot name,

If we define it as predicate: T.() -> Boolean:

persons.filter {
    
     firstName == name }

The readability is it.firstNameso 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 withother scope functions, for example apply, alsothey also have their suitable scenarios. Clear their meanings itand thisapply them to the most suitable scenarios to write beautiful code.

Guess you like

Origin blog.csdn.net/vitaviva/article/details/109144694