Kotlin has been around for quite some time now, and some students have already delved deeply into learning Kotlin and even applied it to their own projects. However, many students may have only heard of Kotlin or have a basic understanding of it. The purpose of this article is to give these students a comprehensive and systematic understanding of Kotlin so that those who are interested can have an easier time learning it in the future.
Like Java and C, Kotlin is a strongly typed language, with variable data types determined at compile time. In contrast, JavaScript and Python are dynamically typed programming languages.
JetBrains is a Czech software company and a well-known IDE developer, providing integrated development environments for various programming languages and platforms, such as Java, Objective-C, JavaScript, PHP, C/C++, etc. Among them, IntelliJ IDEA is the most famous Java integrated development environment, considered the best Java IDE currently available. Moreover, Android Studio is developed by Google based on IntelliJ IDEA, which shows the close collaboration between Google and JetBrains. As seen from the above description, JetBrains is not only strong in its capabilities but also has a natural advantage in language design. Kotlin is a culmination of multiple languages.
We can download all of Kotlin's source code on GitHub. We can also modify the code ourselves and republish it.
JetBrains actually launched Kotlin in 2011. It spent a long time in design, development, and refinement before releasing the first official version in 2016. In May 2017, at the Google I/O developer conference, Kotlin was announced by Google as the official development language for Android.
Kotlin has been referred to as the Swift of the Android platform by programmers.
Kotlin has a large number of syntactic sugars (including function declarations, class creation, collection-related operations, range operators, etc.), Lambda expressions (supported by Java 8), and concise function notation, which will be introduced later.
Please refer to: http://qinghua.github.io/kotlin-syntax-suger/ for a collection of syntactic sugars.
Kotlin has absorbed the advantages of other languages, such as template strings, operator overloading, method extensions, and named parameters. These will be discussed later in the new language features section.
Null safety: Avoid null pointer exceptions. When a variable can be null, it must be declared with a nullable safety symbol (?), otherwise, a compilation error will occur. After declaring a variable as nullable, no exceptions will be thrown at runtime.
Smart type conversion: After using 'is' for type judgment, the compiler automatically performs type conversion. A parent class reference can call a child class interface, but note that the conversion only takes effect within the 'is' code block.
Similar to the relationship between Swift and Objective-C, although the official recommendation is to use the new language Kotlin for Android development, the prerequisite is that the new language must be compatible with the old language (otherwise, it would not be recognized by Google). Therefore, Kotlin's design intention is to be fully compatible with Java.
Mutual invocation: When using Kotlin for Android or Java server-side development, you can import any Java library. Kotlin and Java can call each other.
Mutual conversion: In Android Studio, you can convert Java code to Kotlin code with one click (Code > Convert Java File to Kotlin File). At the same time, Kotlin code can also be decompiled into Java code (1. Tools > Kotlin > Show Kotlin Bytecode 2. Decompile).
Java's API = Kotlin's API.
JetBrains provides a wealth of tool support for Kotlin development. We can directly download the Kotlin Compiler library to compile and run on the command line or use Kotlin in Eclipse by installing a plugin. Now, IntelliJ IDEA and Android Studio can directly use Kotlin for development. As JetBrains said: A language needs tooling, and at JetBrains, that's what we do best!
Let's take a look at a diagram to understand the Kotlin compilation process.
One of the main reasons why Kotlin is compatible with Java is that Kotlin files, after being compiled by the Kotlin compiler, generate Java bytecode. This is almost identical to the bytecode generated by the Java compiler for Java files, allowing the JVM to directly recognize and process Kotlin code's functionality and logic.
When Kotlin calls Java code, the Kotlin compiler analyzes the called Java files so that the Kotlin (kt) files can generate the correct class files. Why is this the case? Let's take an example: Java bytecode has several function call methods, such as invokespecial, invokeStatic, and invokeInterface. The compiler must know the type of the Java function being called in order to generate the corresponding correct bytecode. When Kotlin objects are called in Java code, the class files generated by Kotlin also need to be input to the Java compiler, so that the Java files can generate the correct class files. Once the generated class files are packaged into a JAR file, they can ultimately be used to create an Android APK or be called by a Java server-side application.
We can directly download the Kotlin compiler to examine its compilation process. The Kotlin compiler's code is written in Java, so using the Kotlin compiler requires a Java environment.
1.1 Define variables
Var is used to declare variables, and Val, like Java final, is used to declare constants. The statement does not need to be followed by a semicolon. Variable types can be derived automatically according to variable values. Here, Kotlin's basic types are all objects, using Java wrapper classes (basic types are wrapped as objects).
1.2 Defining functions
Functions are declared using fun as a keyword. The variable type follows the colon of the variable, and the return value follows the colon of the function.
At the same time, we can declare the default values of parameters when defining functions.
You can call a function directly or use named parameters:
Using named parameters can increase readability and reduce overloading of functions.
1.3 Class declaration
The colon of the class name indicates inheritance. The base class of all classes is called Any (not Object, but only equals, hascode, and toString methods). Declare the constructor to indicate the constructor keyword.
You can also specify the constructor directly when declaring a class.
The new keyword can be omitted for object instantiation:
Data class, a class used to store Info data, is actually JavaBeans. Here we use a sentence of code to create a class containing getters, setters, equals(), hashCode(), toString(), and copy().
1.4 Process control
Other process control is basically similar to Java. Here we mainly talk about when expression, which replaces Java switch
In fact, when the expression is finally implemented using if/else.
The original for each loop is retained, and interval control is added
1.5 Set
The Kotlin set is similar to the OC set, which can be divided into variable sets and immutable sets (lists, sets, maps, etc.).
Variable collections in Kotlin wrap Java collections, and it implements a set of immutable collection libraries.
Access:
1.6 Companion object
There are no static properties and methods in Kotlin. If we want to create a single column, we can use the Object keyword to declare the class.
If you want to declare static members in a class, you can use companion objects
inside the class. Use the keyword company object
If called, it is directly called through the class name, property name or function name, just like Java.
2.1 Empty security
How does Kotlin implement empty security?
In Kotlin, object declarations are divided into nullable references and non-null references.
Non-empty reference:
Nullable reference:
Security call operator, writing Can be called null:
Assign a value to a nullable reference through a function call. The returned reference must also be a nullable reference. This eliminates null pointer exceptions during compilation. However, it should be noted here that if the collection returned from Java does not force the nullability check, this is the time when a conversion error exception will occur if null in the Java collection is assigned to a non-nullable reference.
2.2 Extension function
Like the category of OC, API functions can be extended.
We can call directly in any activity
Function extension does not modify the original class. It can be found by decompiling into Java code that function extension is realized by static import.
2.3 String Template
The expression string can contain variables or expressions, starting with the $symbol (which is similar to the EL expression of JSP), such as:
Kotlin is escaped through single quotation marks
2.4 Operator overload
Kotlin provides a fixed name function table for basic operators, such as
Expression | Conversion |
+a |
a.unaryPlus() |
a+b |
a.plus(b) |
...... | ...... |
Example:
Call:
2.5 Lambda expression
Lambda is essentially an undeclared function, which is passed in the form of an expression. Since it is a function, it is composed of three parts: parameter, method body and return value.
Let's see how the complete lambda expression is written:
In braces, the left side of the arrow is the parameter, and the right side of the arrow is the method body and return value. Here, two Int type parameters are passed in and a value of Int type is returned.
Declare a function that accepts a function as a parameter:
The second parameter rightV indicates that a function is accepted. The function has two Int type input parameters and returns an Int type output.
Call:
Using lambda expressions in Android can be written as
The parentheses of the function are omitted. This is not a function-type parameter but is processed by the compiler.
Note: When the listener has multiple interface declarations, it cannot be used like this, such as setOnCheckedChangeListener
3.1 Higher order function
Kotlin calls a function of a higher order that takes a function as a parameter or a function that returns a value. For example, function:
It is a function of higher order. It can be called as follows:
We declare a local function and pass it as a parameter to another function. We can also use lambda expressions to represent function parameters.
3.2 Generics
Generics exist mainly to eliminate template code and type conversion security. The use of generics in Kotlin is basically consistent with Java.
In Java, generics are invariant. For example, although A inherits from B, there is no relationship between List<A>and List<B>. Java uses generic wildcards to implement type variations:
<? Extends T>corresponds to Kotlin's out T producer
<? Super T>In T consumers corresponding to Kotlin
PECS principles: producer extensions, consumer super
But Kotlin is more flexible than Java, for example, you can add type variables when declaring classes or functions.
3.3 Reflection
Get all the information of class methods, properties, class structure, etc. at runtime.
Reflection using Java in Kotlin:
Jc returns a Java class object, through which you can call Java reflection.
Reflection in Kotlin:
You can directly call methods and access properties without using KClass objects (note: if there are overloaded functions or properties with the same name, the following methods cannot be used).
3.4 Coroutine
What is a coroutine?
Coprogramming is a new asynchronous programming method, which uses threads as resources to schedule tasks based on code logic. It is mainly implemented by the compiler.
The program can write linear asynchronous code using coroutine, without callback, which greatly simplifies asynchronous programming. Some thread asynchronous operation coroutines support the suspension and switching of coroutines, which are very lightweight and cost-free.
How to use the coroutine?
Although the coroutine is still in the experimental stage, its functions have been perfect (the latest version 1.2.3 of Kotlin is expected to delete the laboratory status in 1.3). Interested students can refer to:
https://www.kotlincn.net/docs/tutorials/coroutines-basic-jvm.html
Kotlin is not only used for Java, but JetBrains is far more ambitious. Kotlin can also be used for the development of other platforms. Therefore, it is inaccurate to say that Kotlin is a JVM-based language.
Kotlin is used for server development:
Kotlin can be used for Java server development. Java and Kotlin are mutually compatible. We can use any framework on the server side. At the same time, we can keep the old Java code and use Kotlin to write new code. Kotlin's coroutine feature is more helpful for building server applications. IDE support and Sring framework support.
Kotlin for Android development:
Android Studio support. A large number of actual cases. A large number of learnable APP projects. Java compatibility allows all existing Android libraries to be used in Kotlin applications.
Kotlin for JavaScript:
Use the kotlinc js compiler to convert Kotlin code into JavaScript (code that is not Kotlin or standard library will be ignored when compiling). Kotlin provides some standard libraries for JS development, and can use third-party JS libraries.
Kotlin Native:
Kotlin/Native is a technology that compiles Kotlin into a native binary file without any virtual machine. It is still under development, and now only a preview version is available.
Preview version supports Windows, Mac, IOS, Android and other platforms. The Kotlin code will eventually be compiled into a kexe file, which can be directly opened to run.
Source code of a game based on Kotlin/Native: https://github.com/jetbrains/kotlinconf-spinner
The Kotlin multi platform project allows you to compile the same code to multiple target platforms. The currently supported target platforms are JVM and JS, and Native will be added soon.
Multi-platform projects consist of three types of modules:
● Common modules
Common modules only contain platform-independent Kotlin code and Kotlin common standard library code. They also contain platform interface declarations without implementation.
● Platform modules
Platform modules can depend on any modules and libraries available on the specified platform (including Java libraries for the Kotlin/JVM platform and JS libraries for the Kotlin/JS platform).
● Shared modules
Modules that depend on each other with platform modules.
My opinion on Kotlin:
1. It is indeed an excellent language. The language is concise and contains the best features of various languages. However, some of its highlights, such as coroutines and multi-platform support, are still in the experimental and development stages. It may not attract many developers outside of Java and Android (as the JS platform is not widely used).
2. Its interaction with Java allows it to rely on Java for growth. However, its dependence on and compatibility with Java means that it cannot completely replace Java.
3. Although it has gained Google's recognition, the popularity of the Kotlin language has been gradually declining. Before writing this article, it had dropped to 49th place in the TIOBE rankings. I speculate that while Kotlin is favored by experienced programmers, beginners and intermediate players may prefer the familiar language of Java.
4. Its potential is huge, as it has the official support of Google and the strong backing of JetBrains. If Kotlin makes breakthroughs in multi-platform and other experimental features in the future, it will undoubtedly attract more developers.
Learning resources summary:
1. Kotlin official website
http://kotlinlang.org/
2. Kotlin Chinese official website
https://www.kotlincn.net/
3. Google Kotlin project learning examples
https://developer.android.com/samples/index.html?language=kotlin
4. Alibaba engineer teaching series articles
https://segmentfault.com/u/donghaichenguangjian
5. Kotlin coroutines
https://www.jianshu.com/p/9f720b9ccdea
https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md
https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
6. Other articles
https://blog.csdn.net/u013448469/article/details/79403284 Kotlin reflection
https://blog.csdn.net/ztguang/article/details/72511994 Kotlin Native
Tencent WeTest automation compatibility testing provides cloud automation compatibility services, submitting to hundreds of real devices in the cloud for parallel testing. Quickly discover game/app compatibility and performance issues, covering mainstream Android models. At present, it supports all of Tencent's research and operation mobile game projects.