Why use Kotlin
The first phase of the project ended and finally I had time to struggle. For more than a month, Kotlin has insisted on the personal experience of using it for development. Because the difference between syntax and Java is quite big, I really want to give up at first. If it weren't for the project being used, few people would have tried such a niche language, but after getting used to it, I will find out how much time I wasted in writing useless Java code over the years. Kotlin can greatly improve development efficiency on the basis of being compatible with Java. Kotlin has many features, but for development, rapid adaptation and learning are more important. Many times we start using it without understanding the reasons, just as it is impossible for us to study the Retrofit principle thoroughly before using it. As long as it is stable and mature enough and can effectively improve development efficiency, it is worth trying. I am not talented. The reason why I use Kotlin is mainly because it is concise in syntax, supports lambda expressions, and has a powerful when syntax. There is no need to write a semicolon ending. These alone are enough to make me like Kotlin. As for features such as empty security, after all, there are too many null data types on the server and it doesn’t feel that these features are subtly absorbed in actual applications, so that now I’m not used to it when I encounter several Java codes written.
Modification instructions
Suddenly, I was stunned. The influence of Google IO cannot be underestimated. It is better to avoid misleading people's children and modify them, so move the basic knowledge of the previous article and remove the expired links.
Kotlin Basic Syntax
First, let’s talk about a tip for learning Kotlin syntax. Write the code in Java, and then convert Code/Conver Java File to Kotlin File into Kotlin code, or copying Java code to Kotlin file will prompt the conversion. It is also quite convenient. It is easy to understand the differences. At the beginning, I believe you will fall in love with Kotlin after you are unhappy with the habit.
1). Definition
If you forget the Java writing style, you will be very uncomfortable. Kotlin has its own characteristics and should not be bound by Java's thinking. In Kotlin, constants are declared with val, and var, the keyword is in front, and the type is separated by a colon: separated by a rear, and the direct assignment can also be omitted. After the type, the type is accompanied by a question mark, which means that it can be a null type (default null security).
The constant val delays load by lazy{}, the default thread-safe shutdown thread-safe lazy(){}, and the variable var delays load lateinit.
//Constant array int[][][] arrrs = new int[3][2][1];val arrs = Array(3) { Array(2) { IntArray(1) } } //Empty security variablevar str: String = "hello" // Can be empty string variablevar str1: String? = null
2). Conditions
If...else is used normally, but the switch is removed and replaced with a more powerful when. When sub-format can be various expressions that return Boolean
val x = 7 when (x) { in 1..10 -> print("x is in the range") in validNumbers -> print("x is valid") !in 10..20 -> print("x is outside the range") else -> print("none of the above") }
3). Loop
While and do...while are no different from Java, for has greatly changed and several more variants have been added
val list = ArrayList<String>() //Increment for (int i = 0; i < (); i++)for (i in ) { print(list[i]) } //Increment for (int i = 2; i < (); i++)for (i in 2..-1) { print(list[i]) } //Decrement for (int i = (); i >= 0; i--)for (i in downTo 0) { print(list[i]) } //Operate the object in the listfor (item in list) { print(item) } //Enhanced versionfor((i, item) in ()) { print(list[i]) print(item) } //Variable version { print(it) } { print(it) } { i, s -> print(list[i]) print(s) } (object :(Int,String) -> Unit{ override fun invoke(i: Int, s: String) { print(list[i]) print(s) } })
The universal colon
In Kotlin, colon: it is no exaggeration to call it by universal power. It is needed for the type declaration of constant variables, the return value of function, and the inheritance of class.
//val means constant var means variable declarationval name: String = "tutu" //Omit the type descriptionvar age = "23" //Fun represents functionfun getName(): String{ return "tutu" } //Class inheritanceclass UserList<E>(): ArrayList<E>() { //... }
In addition, there is another special place that also requires it, when using Java classes. Kotlin will eventually be compiled into Java bytecode. It is inevitable to use Java classes. The Kotlin syntax is as follows
val intent = Intent(this, MainActivity::)
Class name::No reason just write it like this
Who am I @
In addition to the colon, another important symbol @, I believe there must be many places to use internal classes and anonymous internal classes. In addition, the lambda syntax is supported. Without it, who will tell you which one this and return refer to.
class User { inner class State{ fun getUser(): User{ //Return to User return this@User } fun getState(): State{ //Return to State return this@State } } }
A lazy way
1). Kotlin Features
Java's getter/setter method is automatically converted into attributes, corresponding to the call to Kotlin attributes
public class User { private String name; private String age; public String getName() { return name; } public void setName(String name) { = name; } public String getAge() { return age; } public void setAge(String age) { = age; } }
This Java class is only called in Kotlin
val user = User() //Assignment = "tutu" = "23" //Get the valueval name = val age =
On the contrary, Kotlin's attributes automatically generate Java's getter/setter method, which is convenient for calling in Java. The same definition is in Kotlin.
class User { var name: String? = null var age: String? = null }
Our getter/setter method is sometimes not that simple, so we need to customize getter/setter, set the get()/set(value) method on another line to implement a singleton commonly used in Java. This is just for the sake of display. Singleton has a simpler method to implement in Kotlin. Just create an object at the package level.
class User { companion object { @Volatile var instance: User? = null get() { if (field == null) { synchronized(User::) { if (field == null) field = User() } } return field } } var name: String? = null var age: String? = null }
The focus of custom getter/setter is on field, just like the Java-like this refers to the current class. Field refers to the current parameter. Directly using the parameter name instance instead will not report an error, but the singleton will have no effect.
2). String template
The code of splicing strings in Java is very poor, and splicing Kotlin strings becomes very concise. You just need to add the parameter name after $, and add the complex parameters to {}
val user = User() //Assignment = "tutu" = "23" //Get the valueval name = val age = var userInfo = "name:${}, age:$age" //Output result:name:tutu, age:23
3). lambda
At first I thought that lambda was very advanced and I couldn’t understand it at all. In fact, it was very simple to save the interface name, method name and parameter type and add it ->. If you understand this, I won’t introduce it.
New face
1). Delay loading
2). Process control
Empty judgment
Kotlin's empty security design requires null judgment processing when using parameters that declare nullable. One is to throw an empty exception like Java, add the field after adding it!!, and the other is to skip it without processing, add the field after adding it?
//Add to the type after it means that it can be emptyvar age: String? = "23" //Top a null pointer exceptionval ageInt = age!!.toInt() //Skip it without processingval ages = age?.toInt()
Things to note
The internal classes and parameters are public by default, and private in Java
The class defaults to non-inheritable (final). If you want to be inherited, you must declare it as open or abstract.
The static keyword was cancelled, and the static methods and parameters were written uniformly in the component object block.
It is visible in the internal module, inner class
The above is just a summary of the syntax that is frequently used. You can basically read Kotlin code if you learn to do something. When encountering some problems, Google will check it quickly. As for intelligent conversion, type derivation, etc., it goes without saying that you will naturally like it after using it. Of course, this is just the basic syntax of kotlin, which is convenient for Java to quickly become familiar with kotlin. Please read relevant materials if you study in depth.