1

The feeling after using Kotlin in depth

I wrote a rough feeling about kotlin before, and briefly described several advantages of kotlin, such as the judgment of empty objects.

After exploring kotlin for a period of time, I found that these advantages are far from all of kotlin, so I wrote an in-depth article about the experience of using kotlin.

A recent project started to use the language kotlin comprehensively, and also had more opportunities to experience the new features of kotlin.

The feeling of using kotlin a lot is that whenever you design a solution to a problem, your unique inspiration can be satisfied by kotlin, which can greatly improve your programming experience, which has never been done in any language before. feeling.

code that can be designed

The use of kotlin makes me feel that I am not controlled by the language, you can control the language itself.

When you need to design your own tools, kotlin is a huge help for you, it allows you to create a useful and unique tool anytime, anywhere without making you feel obtrusive.

For example, when you get tired of writing the following

 val isError = true
if (isError) {
        throw Exception("")
}

you can

 fun Boolean.ifThr(message: String) {
    if (this) {
        throw Exception(message)
    }
}

val isError = true

isError.isThr("")

From there you have a facility to throw exceptions directly through Boolean objects.

Maybe you also want to print a log when an exception is thrown.

 fun Boolean.ifThr(message: String, func: (() -> Unit)? = null) {
    if (this) {
        func?.let { it() }
        throw Exception(message)
    }
}
val isError = true

isError.isThr("") // 不打印日志,直接抛出
isError.isThr("") { // 打印日志,并抛出
        log.error("")
}

You can even let the Boolean value be empty to throw an exception without judgment.

 fun Boolean?.ifThr(message: String, func: (() -> Unit)? = null) {
    if (this == true) {
        func?.let { it() }
        throw Exception(message)
    }
}
val isError :Boolean? = null
isError.ifThr("")

You can also extend the method of List to determine whether a set of results are all true.

 fun List<Boolean>.allTrue(): Boolean {
    this.forEach {
        if (!it) {
            return false
        }
    }
    return true
}

The above method shows several features. They may not be very powerful when used individually, but when combined, you will be surprised at its expressiveness and convenience, which can reduce your code a lot while taking into account to a combination of readability, elegant implementation, and practicality.

This is the power of kotlin, if you want, you can design elegantly first, and then code elegantly.

Of course, elegance is just a by-product, it's what it really does.

It allows you to design a coding mode in a low-cost way, which can help you better deal with the details of the implementation of business requirements, so as to focus on the implementation of business requirements, greatly reduce the occurrence of logic errors, and significantly reduce corrections. wrong cost.

The encoding process is no longer interrupted

You may have encountered such a situation (take elasticsearch as an example)

 val searchRequestBuilder = SearchRequest.Builder()
            .source {
                it.filter { it.includes("id") }
            }
            .index(modelIndexNames)
            .query(query)
            .sort {
                it.field(FieldSort.Builder().field("id").build())
            }
            .size(10000)
        sort?.let { searchRequestBuilder.searchAfter(it) }
        searchRequestBuilder.build()

You can see that the original design idea of SearchRequest is that the use process is continuous and uninterrupted, but once you encounter a place where you need to judge in the middle, you have to interrupt this process, although it does not affect the overall function, but Slightly less readable.

It can be optimized to the following writing

 val searchRequest = SearchRequest.Builder()
            .source {
                it.filter { it.includes("id") }
            }
            .index(modelIndexNames)
            .query(query)
            .sort {
                it.field(FieldSort.Builder().field("id").build())
            }
            .apply {
                sort?.let { searchAfter(it) }
            }
            .size(10000)
            .build()

In this way, a piece of code that is bound to be interrupted in java can be written fluently in kotlin.

Doubts during use

In my opinion, kotlin is full of advantages.

But as my understanding and writing of kotlin deepened, I began to worry gradually.

Whenever I write some advanced writing in kotlin, I am not sure whether the writing can be fully absorbed or understood by junior engineers.

Of course, this may only be due to the complexity of the business logic. Simple requirements will not use so many advanced features. Instead of worrying about grammar issues, it is better to worry about whether other people can understand the business logic.

Mainly want to discuss the future

I think kotlin is definitely qualified to be widely accepted, and it is not a problem to completely replace java in most scenarios.

However, in the process of completely kotlinizing this project, combined with my current company experience and some online forums, I am not very optimistic about the future of large-scale application of kotlin in the domestic programming industry.

First of all, I think that the major domestic manufacturers themselves, the code professional level of large-scale java collaboration is really not high, at least not the top level. In the first two years of my work, I was attracted by the online Alibaba java development manual, and felt that the domestic large-scale cooperation was not high. The factory product is not bad, and there is no problem with the manual itself.

It wasn't until 2021, when I started diving into framework serialization and studying fastjson, that I began to understand that what is popular is not necessarily good. As I am currently writing this article, the number of stars for fastjson on github is 24.9k, while jackson is only 7.6k.

Even Alibaba's own nacos project does not use fastjson. Of course, the source code of nacos is better than fastjson, but it is still much worse than the top foreign open source projects.

In China, there is a search platform like Baidu that has already been laid flat, and then there is gitee, which was originally called Code Cloud Rush, the page design is very backward, and it is inexplicably packed with many functions. The first open source platform in China.

I have to have this kind of pessimistic apprehension. It is very difficult to expect the technological environment built by such Internet companies to promote new things.

Not to mention that in many small companies, they do not seek progress in technology, but only want to quickly fulfill their needs. Without the promotion of external large Internet companies, it is even more difficult to contact new things.

But I still have some hope, hoping that in the future, a technology-loving environment will be born in the domestic environment, and I will no longer be bound by inherent thinking and have the courage to explore new realms.


zxdposter
3.9k 声望3.5k 粉丝