In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you how to use Kotlin to expand the relevant knowledge points, the content is detailed, the logic is clear, I believe most people still know too much about this knowledge, so share this article for your reference, I hope you can get something after reading this article, let's take a look at it.
In fact, customers completed their back-end technology selection as early as the beginning of last year, and Kotlin has become the main language for building back-end micro services for projects at that time. So I didn't give a good answer in these sharing, and the question itself caused me to think.
First of all, let's take a look at the features of the Kotlin language, which are officially listed as four remarkable features:
Concise Consice
Secure Safe
Friendly development tool Tool-friendly
Interoperability Interoperable with Java
Concise Concise
The simplicity of Kotlin is reflected in many aspects. For Java programmers, the most direct manifestation is that the semicolon is omitted directly in the Kotlin syntax, and the new keyword is omitted when constructing an instance of a class. Here is a standard Kotlin code:
Fun sayHi (name: String): String {val sb = StringBuilder (str = "Hi") sb.append (name) return sb.toString ()}
Let's take another look at the sample code on the official website of Kotlin to experience the simplicity of Kotlin:
Data class Customer (val name: String, val email: String, val company: String)
A simple line of code implements a Pojo that contains constructor and the default getters, toString, equals, hashCode and copy implementations, while the same java implementation requires about 50 lines of code, even with the help of Lombok.
Kotlin also encapsulates Java collection classes and provides a wealth of collection operations. At the same time, it combines very concise Lambda expressions to make the call more concise.
Val numbers = 1.. 10 val doubles = numbers.map {it * 2} val sumOfSquares = doubles.fold (0) {xenery-> xonomy}
In addition to these, Kotlin also provides many features such as string templates, standard function libraries, and operator overloading, which make the code very simple and easy to read, greatly improving the developer's experience.
From the point of view of the actual project, the simplicity of Kotlin is very obvious in the amount of code. A Spring Boot microservice that provides 24 API has about 8000 lines of code written through Kotlin (including test code). If microservices of the same size are written in Java, the amount of code will be much larger than this number.
Secure Safe
One of the most common traps in many programming languages, including Java, is to access null pointers, resulting in null pointer exceptions. The security of Kotlin is mainly reflected in its support for Null-Safety. The ability to make code aware of possible NullPointerException during compilation, so that Java developer can easily get rid of NullPointerException.
Var output: String output = null / / Compilation error val name: String? = null / / Nullable type println (name.length ()) / / Compilation error
At the same time, Kotlin also provides some features of automatic transformation and type inference, which not only provides security check, but also brings convenience.
The following is also an example from the official website. Kotlin automatically completes the conversion from Any to Invoice after getting true from type checking:
Fun calculateTotal (obj: Any) {if (obj is Invoice) obj.calculateTotal ()}
Friendly development tool Tool-friendly
There is no need to say much about this feature, to quote the original phrase of Aojiao on the official website is "It's what we do best!"
Interoperability Interoperable with Java
To put it simply, this feature is that Kotlin and Java can call each other.
This means that we can use any existing Java libraries to build our applications, so that we can enjoy the pleasant programming experience of Kotlin without giving up everything we are familiar with.
... Import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.JpaSpecificationExecutor... Interface AreaRepository: JpaRepository, JpaSpecificationExecutor {fun existsByAreaId (id: UUID): Boolean fun findOneByAreaId (areaId: UUID): AreaEntity?}
The example is a Spring JPA-based Repository written in Kotlin on the project, and you can see that thanks to the nature of Interoperable, we can rely on a complete Java ecosystem when trying to use Kotlin. We can still use the frameworks, build tools, development tools, and testing tools that we are familiar with.
How do I start?
After seeing such attractive language features, you may be tempted to try Kotlin. But the reality may be that the project has been under way for some time, and we have built a lot of functionality for the project with Java. Introducing a new language at this time may bring some risk to the project. So how can we start?
Writing unit tests using Kotlin
If you are conservative, you can start trying to write unit tests only through Kotlin in your project, and thanks to the Interoperable feature, we can easily use Kotlin to write unit tests for Java classes. In this way, you don't have to worry about the risk of trying Kotlin to your business code, and you can also try the various features of the Kotlin language while writing unit tests.
Use Kotlin to extend
You can also use Kotlin to enrich the Library used in the project, and Kotlin Extensions to extend the original types without inheritance. Or write tool classes to serve the project directly through Kotlin.
/ / Extensions.kt fun String.lastChar () = this.get (this.length-1) fun KPerson.fullName () = "${this.firstName} ${this.lastName}" / / String template / / Java JUnit test Test public void lastChar () throws Exception {assertEquals ('nasty, Extensions.lastChar ("Kotlin"));} Test public void fullName () throws Exception {KPerson k = new KPerson ("Foo", "Bar", Gender.MALE, 18); assertEquals ("Foo Bar", Extensions.fullName (k)) }
Using Kotlin to rewrite microservices
If you are using Spring Boot-based microservices, you can pick a lower priority service and gradually rewrite it through Kotlin. You will find that this transition is going to be extremely smooth. Because Kotlin won't change the way you used to build microservices through Spring Boot.
All three methods allow you to try Kotlin when the risk is manageable. Let you feel the wonderful programming experience brought by the Kotlin language, while making the whole team familiar with the Kotlin language. You will find that it is really easy for a Java programmer to learn Kotlin, and once you start, you can never go back.
These are all the contents of this article entitled "how to use Kotlin to expand". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.