In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the mixed development of Kotlin and Java example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
I. Frontier
If you have studied other programming languages, you will find that the syntax of Java is trembling, but why didn't we give up the programming language Java? Because JVM is a very good platform, and the proportion of Java programmers in China is too high. This is caused by the burden of history. Leaving aside Python, the syntax is definitely not one level simpler than Java, and even C # is much more beautiful than Java syntax.
We know that the Java program runs like this:
Write source code (.java)-> compile source files (.class)-> JVM virtual machine loads class files into memory, execute
In that case, if there is a language that can also be compiled into class files and then loaded by JVM, and the language syntax is more beautiful and concise than Java, would you be happy to use it? Then this excellent language is Kotlin. Kotlin, his journey goes like this:
Write source code (.kt)-> compile source files (.class)-> JVM virtual machine loads class files into memory and execute.
In 2017, Google announced that Kotlin has become the official development language of Android, which shows that Kotlin is good.
Of course, with the development of Kotlin, Kotlin is not only a language on the JVM platform, but also can compile Kotlin code into JavaScript, and there will be Kotlin Native in the future, so Kotlin definitely has great potential.
Second, prepare before learning Kotlin
If you want to do good work, you must first sharpen its tools. First of all, we must choose a good IDE,Kotlin developed by JetBrains, so of course we have to use JetBrains's own IDE, we will choose IDEA! I believe that the vast majority of Java developers are using it.
Let's just build a new ordinary project.
If we want to write Kotlin code, it's very simple, right-click, and create a new Kotlin file.
After creating a new file, IDE will prompt us to configure it. Just follow the prompts to configure it.
III. Brief introduction to Kotlin grammar
If you have already studied Java, getting started with Kotlin will be very quick.
Let's write a Hello world first!
Open our newly created kt file and enter the following code:
Fun main (args: Array) {print ("hello world")}
Let's review the Java code again:
Class HelloWord {public static void main (String [] args) {System.out.println ("Hello world");}}
By comparison, Kotlin has very little code. In our Java, methods must be written in a class, while our Kotlin supports package-level functions, and static methods do not need to be written in a class. And Kotlin does not need a semicolon at the end of each sentence.
In Kotlin, all variable declarations need to be decorated with val or var and support type inference, but you should note that Kotlin is a static language.
Variable declaration format: val/var variable name (: type, but not written, will be automatically inferred)
For example, val iTunes 1 and val i:Int = 1 have the same effect.
Var iTunes 1 and val iTunes 1 are translated into Java respectively as follows:
Final int i=1int iTunes 1
Variables modified by val will be translated into final keywords similar to those in java, which is a major feature of Kotlin. For all classes in Kotlin, methods are final by default.
The editor suggests that you should take a look at the bytecode translated from Kotlin to Java when you are a beginner. We already have related plug-ins for IDE:
After clicking, the screen appears as shown in the figure:
Then click the button in the red box, and it will show that our Kotlin has been translated into Java.
Excellent expression
Let's look at the following code:
What is the difference between him and our if else in Java?
Our expression can also have a return value, be careful not to write return xxx, because return will jump out of the method. In Kotlin, the last sentence of a conditional expression can be used as a return value, a small skill that can be said to be very useful, as well as try and catch.
Enhanced switch
As a senior Java developer, I seldom use switch. On the one hand, switch must operate on the same type, with a single function, which may not be as powerful as if, and frequent use will increase code coupling, and it will generally use polymorphisms combined with related design patterns instead.
Let's take a look at the enhanced version of switch expression when in Kotlin:
When the first case branch is satisfied, the expression ends. Similarly, it may also be used as an expression, each branch of the last sentence can return a value, and then give a variable to receive, is not 10, 000 times more powerful than switch!
Template string
This function is very useful, we may often have the pain of concatenating strings in java, it's okay, Kotlin can solve your pain, let's take a look at this code:
We use ${} in the string, and you can write Java code in curly braces, which achieves the effect of a template string. Of course, you can also do this:
You can output this variable directly using $plus the variable name. So if we want to output $, then we need to escape, just like Java, using\.
Wrapper classes and basic data types no longer exist
In Java, all basic data types such as int, double and so on have their corresponding wrapper classes, which no longer exist in Kotlin, and all use Int, Double, Float, String...
When compiling, Kotlin will intelligently choose basic data types or wrapper classes according to our situation, so there is no need for programmers to worry about it.
Data class, goodbye, Java bean.
The general process of writing JavaBean is to write a class class, which writes several fields, then gives several get/set methods, and sometimes overrides the toString, equals, and HashCode methods.
These processes are actually a bit repetitive, if we write a class using the data class provided by Kotlin:
Data class Person (val username:String,val age:Int)
In this way, we have written a data class. In a short sentence, we can also see from the declaration that we have defined two attributes, username and age, for the class Person. We use the IDEA plug-in to translate it into Java code:
Public final class Person {@ NotNull private final Stringusername; private final int age; @ NotNull public final String getUsername () {return this.username;} public final int getAge () {return this.age;} public Person (@ NotNull Stringusername, int age) {Intrinsics.checkParameterIsNotNull (username, "username"); super (); this.username = username; this.age = age } @ NotNull public final String component1 () {return this.username;} public final int component2 () {return this.age;} @ NotNull public final Person copy (@ NotNull String username, intage) {Intrinsics.checkParameterIsNotNull (username, "username"); return new Person (username, age) } / / $FF: synthetic method / / $FF: bridge method @ NotNull public static Person copy$default (Person var0, String var1, int var2,int var3, Object var4) {if ((var3 & 1)! = 0) {var1 = var0.username;} if ((var3 & 2)! = 0) {var2 = var0.age;} return var0.copy (var1, var2) } public String toString () {return "Person (username=" + this.username + ", age=" + this.age + ")";} public int hashCode () {return (this.username! = null? This.username.hashCode (): 0) * 31 + this.age;} public boolean equals (Object var1) {if (this! = var1) {if (var1 instanceof Person) {Person var2 = (Person) var1; if (Intrinsics.areEqual (this.username, var2.username) & & this.age = = var2.age) {return true }} return false;} else {return true;}
Data class is so amazing that Kotlin will automatically add get/set methods and tostring, euqals, hashcode methods for us when compiling.
Note, however, that the Kotlin class is final by default, so my data class cannot be inherited, and it has no parameter-free constructor. If you use MyBatis directly in this way, you will report that this class cannot find a no-parameter constructor.
In order to solve these problems, Kotlin officially recommended the no-arg plug-in to solve this problem. If you want the data class compile time to remove the final keyword, you can use the Kotlin official plug-in all-open plug-in to solve this problem.
Beside the point, in Spring5, Spring has made a lot of optimizations specifically for Kotlin. For example, the underlying implementation of AOP, I believe people with some skills know that spring will dynamically generate a subclass for this class using CGLIB technology. Our Kotlin class defaults to final, so if we write AOP in Kotlin, if we want our AOP class to work properly, we must precede the class with open. But every time it is troublesome to write, our index official has also launched a kotlin-spring plug-in, which can automatically final keywords for these classes.
Null pointer exception no longer exists
All types in Kotlin distinguish between non-nullable and nullable types, such as nullable Int, that is, Int?,. If this type allows null, we will add a? after this type, no? Then this type cannot be empty!
For example, after we define a method and a parameter type, we specify?, we can pass Null, otherwise we can't, or add! Forced delivery.
Kotlin has too many stunts, including when defining methods, I can specify default values for parameters, and I can pass them when I specify a parameter name when calling. At compile time, Kotlin will generate several overloaded Java methods. Of course, this is only a drop in the bucket. The most powerful thing about Kotlin is high-order functions and functional programming, and supports science and technology. Support for operator overloading, you can add extension methods to classes, which is excruciatingly powerful.
At the same time, Kotlin also supports Concord programming (this one is not very mature at present). Due to the limited space, if you are interested, I can do another project explanation.
Write singleton classes
Singleton pattern is one of the most commonly used design patterns among 23 design patterns. It also provides us with a very quick way to write singleton classes in Kotlin, which requires only one line of code to implement the singleton:
Object Singleton
Yes, you read it correctly, only need to write 2 words, object stands for declaring a singleton class, Singleton is the singleton class name, isn't it very Easy?
Let's test it:
To add here, because Kotlin supports operator overloading, in Kotlin, the double equal sign is equivalent to calling the equals method, and the third equal sign is the comparison memory address. If we see that the output here is true, it means that the output is the same object. Let's take a look at his bytecode, translated into Java code:
As you can see, it is a simple singleton pattern. The construction method is not shown, but it is actually privatized. In fact, we can still destroy his singleton by reflecting to modify the constructor access modifier.
Expansion method
I believe that if you have done Java development for many years, you must have a large number of Util classes on hand, such as DateUtils, HtmlUtils, StringUtils and so on. In fact, this is all caused by the language Java. When you learn to extend methods, you will bid farewell to Util.
For example, if we want to judge whether the length of a string is greater than 0, we just have to judge that it is not null and the length is greater than 0. If we use Java to implement it, I believe you will write a StringUtils, so how can we use the extension method of Kotlin to achieve it?
We extend an isNullOrEmpty method for String, and how to return false indicates that the length is greater than 0.
When we define a method, we add the corresponding class name in front of it to become an extension method.
Fun String.isNullOrEmpty (): Boolean {return! (this.isNotEmpty ())}
This code can be written anywhere.
We write test class calls:
Isn't it natural. Say goodbye to Util! In fact, our Kotlin provides a large number of extension methods in many JDK classes, such as String class, collection class, IO class, and so on. For example, if we learn a text file, we only need one sentence:
Val file = System.IO.File ("d:/1.txt") println (file.readText ())
ReadText is the extension method that Kotlin wrote for us, and there are many similar ones. Therefore, using Kotlin will certainly greatly improve your work efficiency.
Operator overloading
In Kotlin, each operator corresponds to a method in this class, and operator overloading can be done if there is a corresponding method implementation in that class.
Even the calling method is the same, for example, if we call a (b), it is equivalent to a.invoke (b):
The expression corresponds to the conversion a + ba.plus (b) a-ba.minus (b) a * ba.times (b) a / ba.div (b) a% ba.mod (b) a..ba.rangeTo (b) a [I] a.get (I) a [I, j] a.get (I, j) a [I _ 1,... , iTunn] a.get (iTun1,... , iMagne) a [I] = ba.set (I, b) a [iMagnej] = ba.set (iMagnej, b) a [i1, … , iTunn] = ba.set (iTun1,... , ain bb.contains (a) a! in baub.cake (a) a [I] a.get (I) a [I, j] a.get (I, j) a [I _ 1,... , iTunn] a.get (iTun1,... , iMagne) a [I] = ba.set (I, b) a [iMagnej] = ba.set (iMagnej, b) a [i1, … , iTunn] = ba.set (iTun1,... , ostensibly, b)
For example, if we want to calculate a few days after a date, if we use Java to do it, I believe you must write no less than 10 lines of code, and it will be very painful. In Kotlin, with operator overloading, I have a good idea to let data+1 return the date one day later, isn't that great?
Do what you say, let's do it:
From the table above, we can see that the method to be overloaded is plus. But the Date class is provided by JDK, so how can we add a method for it? Yes, as we said earlier, Kotlin supports class extension methods. We extend a plus method for the Date class, and the combination of extension methods and operator overloading will be recognized.
By the way, the point hasn't been said yet, how to define operator overloading? It is not enough to write the corresponding method, but also to add the operator keyword before fun. So, we write the following code:
Operator fun Date.plus (nextVal:Int): Date {val calendar = GregorianCalendar () calendar.time = this calendar.add (Calendar.DATE, nextVal) return calendar.time}
To make it easier to view the date string, we extend a stringFormat method, and since the "yyyy-MM-dd" format is too common, we give it a default value.
Fun Date.stringFormat (formatType:String = "yyyy-MM-dd"): String {return SimpleDateFormat (formatType) .format (this)}
Write the test method:
Absolutely, I have to sigh the greatness of Kotlin!
IV. Mixed development of Kotlin and Java
Because Kotlin and Java are compiled into class files, Kotlin and Java are naturally compatible and 100% compatible. In Kotlin, you can feel free to use the class defined in JVM, or you can write your own Java class, and you can have both Java class and Kotlin class in the same project.
For example, if you define a data class Person class, in the same project, you can create a new Java class, using Person person = new Person ("Xiaoming", 12); this is no problem at all. Similarly, classes that you define in Kotlin can also be used in Java. From now on, use Kotlin, don't be afraid, even if there is a place where you are worried that you are not familiar with Kotlin and can not achieve it, you can also use Java at this time. It is 100% compatible and can be used by all libraries in Java.
A diagram of Kotlin usage SSM is attached here:
As you can see, the source code is Kotlin, so we can also use the Spring framework and attach the project source file.
File in front of the icon with K in the lower right corner are Kotlin files, you can see, Kotlin and Java is very good.
So, how do we call things like extension methods, operator overloading, default parameters, etc., with Java?
It's a pity that due to the limitation of Java syntax, we can't use it like Kotlin, but that doesn't mean we can't call it with Java. We can only use it as a common method in Java.
V. Summary of Kotlin and Java
Personally, it is only a matter of time before Kotlin replaces Java. Nowadays, the update speed of Java has been very slow, and more and more Java developers have turned to Kotlin. Even if your current project has been written in Java a lot, you can still use Kotlin from today, which is compatible with Java 100%, which is its biggest feature. In the future, Kotlin will certainly step out of the JVM platform, to be exact, it has already stepped out, and the future will become more and more powerful.
Thank you for reading this article carefully. I hope the article "sample Analysis of mixed Development of Kotlin and Java" shared by the editor will be helpful to you. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.