Time to program with Kotlin

Children's shoes engaged in Android development know that since Kotlin was designated as the official language for Android development at the Google I/O conference last year, Kotlin has become the goal of every developer's learning. Indeed, Kotlin with its unique charm is Attract this traditional Java program developer. Perhaps many children's shoes have already studied Kotlin in depth and have even used it in their own projects, but many students may have only heard of Kotlin or have a simple understanding of it. This article will introduce Kotlin-related content from a macro perspective. .
Before introducing Kotlin, let's come to Amway first. The book about Kotlin that I started writing at the end of last year will be published next month. If you are interested, you can pay attention to it. The catalogue is as follows.
write picture description here

Introduction to Kotlin

Kotlin is a static programming language developed by JetBrains for JVM, Android and browsers. Currently, it has been open sourced under the license of the Apache organization. Using Kotlin, developers can easily develop mobile Android applications, server programs and JavaScript programs. Kotlin can compile code to Java bytecode, but also to JavaScript, which is convenient to run on devices without a JVM.
Kotlin is open source, which means that we can download all the source code of Kotlin on GitHub, modify it and then publish it. The open source address of Kotlin on github is:
https://github.com/JetBrains/kotlin .

JetBrians

A Czech software company is a well-known IDE developer, providing corresponding integrated development environments for many development languages ​​and platforms, such as Java, OC, JavaScript, PHP, C/C++, etc. The most famous of them is IntelliJ IDEA, an integrated development environment for Java, known as the best java IDE at present. And Android Studio is developed by Google based on IntelliJ IDEA, which shows that the cooperation between Google and JetBrains is also relatively close. From the above description, we can also see that JetBrains is not only strong, but also has a natural advantage in language design. Kotlin is the culmination of many languages.

Advantages of Kotlin

So, what are the advantages of Kotlin over languages ​​such as Java?

1. The syntax is concise, attracting the advantages of other languages

Kotlin provides a lot of syntactic sugar (there are a lot of concise syntax for function declaration, class creation, collection-related, range operators, etc.), Lambda expressions (supported by Java8), and concise function notation. And absorbs the best of other languages: template strings, operator overloading, method expansion, named parameters, etc.

2. Security

Kotlin provides the safety character "?", when the variable can be null, the nullable safety character must be used? make the declaration, otherwise you will get a compile error. In addition, Kotlin also provides an intelligent type judgment function. After using is type judgment, the compiler automatically performs type conversion, and the parent class reference can call the subclass interface. Note that the conversion only takes effect in the code block of is.

3. Fully compatible with Java

Another advantage of Kotlin is that it is 100% compatible with Java, and Kotlin and Java can call each other. Using Kotlin for Android or Java server development, you can import any Java library.

In Android Studio, you can convert Java code to Kotlin code with one click (Code > Convert Java File to Kotlin File.), and Kotlin code can also be decompiled into Java code (1.Tools>Kotlin>Show Kotlin Bytecode 2.Decompile).

4, IDE tool support

On the latest version of Android Studio 3.0 officially released by Google, Kotlin has been integrated by default. For some old versions, Kotlin can also be integrated by means of plugins. Therefore, using the IDE provided by JetBrains can provide the best environment support for Kotlin development. As JetBrains says: a language needs to be tooled, and at JetBrains, that's where we do it best!

How Kotlin is compatible with Java

All Kotlin can be 100% compatible with Java, so how is Kotlin compatible with Java? The following is a compilation flow chart of Kotlin.
write picture description here

One of the main reasons why Kotlin is compatible with Java is that Kotlin files will generate Java bytecodes after being compiled by the Kotlin compiler. This is almost indistinguishable from the bytecode generated after the Java file is compiled by the Java compiler, so that the JVM can directly recognize and process the functionality and logic of the Kotlin code.

When Kotlin calls Java code, the Kotlin compiler analyzes the called Java file so that the kt file can generate the correct class file. Why do you say that? For example, Java bytecode has several function calling methods: invokespecial, invokeStatic, invokeInterface, etc. The compiler must know what type of Java function is called to generate the corresponding correct bytecode. When the Kotlin object is called in the Java code, the class file generated by Kotlin must also be input to the Java compiler, and then the Java file can generate the correct class file. After the generated class file is packaged into a jar package, an Android APK can finally be generated, or it can be called by the Java server.

Of course, we can download the Kotlin compiler directly to view its compilation process. The code of the Kotlin compiler is written in java, so using the Kotlin compiler must have a java environment.

Kotlin language basics

Basic Features

1. Variable Definition

write picture description here
In Kotlin's grammar rules, var is used to declare variables, val is similar to Java final, used to declare constants, and a semicolon is not required after the statement. The variable type can be automatically deduced according to the variable value. Here, the basic types of Kotlin are all objects, and the Java wrapper class is used (the basic type is wrapped into an object).

2, function definition

write picture description here
Functions are declared with the fun keyword, the variable type is after the colon of the variable, and the return value after the colon of the function. At the same time, Kotlin supports declaring the default value of the parameter when the function is defined. For example
write picture description here
, when the function is called, it can be called directly, or named parameters can be used, for example:
write picture description here

3. Class declaration

write picture description here
The colon of the class name indicates inheritance. The base class of all classes is called Any (but not Java's Object, which only contains equals, hascode, and toString methods). When declaring a constructor, specify the constructor keyword. E.g:
write picture description here

Of course, you can also specify the constructor directly when declaring the class, and you can instantiate the object without writing the new keyword.
write picture description here

4. Flow Control Statement

Kotlin's other process control is basically similar to Java. Here we mainly talk about when expression, which replaces Java's switch. For example:
write picture description here
when expression is actually implemented using if/else, Kotlin retains the original for each loop, while adding interval control. E.g:
write picture description here

5. Collection

Kotlin's collections are similar to OC's collections, and are divided into mutable collections and immutable collections (lists, sets, maps, etc.). The mutable collection in kotlin wraps the Java collection, and it implements a set of immutable collection libraries.
write picture description here
The way to call the above collection is as follows:
write picture description here

6. Companion object

There are no static properties and methods in Kotlin, if we want to create a single column, we can declare the class using the Object keyword.
write picture description here

If you want to declare a static member in a class, you can use a companion object inside the class, and the companion object uses the keyword companion object.
write picture description here
Companion objects are called by class name, property name or function name, just like in Java.
write picture description here

new features

1. Air safety

In Kotlin, object declarations are divided into two types: nullable references and non-nullable references. The definition of a non-null reference is as follows:
write picture description here
while a nullable reference needs to use the safe character "?", for example:
write picture description here
when calling, it also needs to use the safe call operator, which is written as ?. For example,
write picture description here
assigning a value to a nullable reference through a function call must also return a nullable reference, which prevents null pointer exceptions during compilation. However, it should be noted here that if the collection returned from Java will not be forced to do nullability checking, this is the time when a conversion error exception will occur if you assign null in a Java collection to a non-nullable reference.

2. Extension function

Like OC's Category, Kotlin also supports extension of API functions.
write picture description here
Then, we can call it directly in any Activity.
write picture description here
By decompiling into Java code, it can be found that the extension of the function is essentially implemented by static import.

3. String template

Strings can contain variables or expressions, starting with a $ sign (this is a bit like JSP EL expressions), for example:
write picture description here

4. Operator overloading

Kotlin provides a fixed-name function table for basic operators. This part is more. For this content, readers can visit the following content: Kotlin operator overloading .
write picture description here

The call is as follows:
write picture description here

5, Lambda expression support

The essence of a lambda expression is an undeclared function that is passed as an expression. Since it is a function, it consists of three parts: parameters, method body and return value. For example, the following is a typical lambda expression.
write picture description here
As you can see, within the curly brackets of the lambda expression, the left side of the arrow is the parameter, and the right side of the arrow is the method body and return value.
write picture description here

To call the above function, you can use the following calling method.
write picture description here

Advanced Features

1. Higher order functions

Functions that take functions as parameters or return values ​​are called higher-order functions in Kotlin. For example,
write picture description here
the way to call higher-order functions is as follows:
write picture description here
Of course, we can also declare a local function and then pass it as a parameter to another function, and we can also use Lambda expressions to represent function parameters.
write picture description here

2. Generics

The existence of generics is mainly to eliminate template code and type conversion safety. The use of generics in Kotlin is basically consistent with Java.
write picture description here
Generics are immutable in Java. For example, although A inherits B, there is no relationship between List and List . Java implements type variation through generic wildcards:

3. Reflection

Reflection is a behavior of a program running in the JVM to detect and modify the runtime. Through reflection, the properties and methods of an object can be obtained at runtime. The function of dynamically obtaining information and dynamically calling object methods is called reflection mechanism. Reflection can get all the information of a class, such as methods, properties, class structure, etc.
An example of using Java reflection in Kotlin is as follows:
write picture description here
jc returns a Java class object, which can be used to invoke Java reflection content.

Reflection in Kotlin is as follows.
write picture description here
When you want to call a specific object, you can directly call methods and access properties without going through the KClass object. E.g:
write picture description here
write picture description here

4. Coroutines

A coroutine, also known as a micro-thread, is a non-priority subroutine scheduling component that is started by a launch coroutine builder. Coroutine is essentially a lightweight thread in user mode. The calling method of coroutine is the same as that of sub-thread, but the use of coroutine is more convenient and flexible, but the use of coroutine is not as extensive as that of sub-thread.
As a new asynchronous programming method, coroutine uses threads as resources and implements scheduling between tasks based on code logic. Programs using coroutines can write linear asynchronous code without callbacks, which greatly simplifies asynchronous programming. The following is an example of the use of coroutines:
write picture description here, you can visit the following link for more information about coroutines:
https://www.kotlincn.net/docs/tutorials/coroutines-basic-jvm.html

Cross-platform development

Multi-platform support

Kotlin is not only used for Java, it can also be used for web js and iOS development, so it is inaccurate to say that Kotlin is a JVM-based language on the market. Through the Kotlin Native feature provided by Kotlin, Kotlin can use cross-platform development features. The cross-platform supported by Kotlin is shown in the following figure.
write picture description here

1. Kotlin is used for server-side development

Using Kotlin can be used for Java server-side development. The mutual compatibility between Java and Kotlin, we can use any framework on the server side, and at the same time we can keep the old Java code and write new code in Kotlin. Kotlin's coroutine feature is more helpful for building server-side programs. IDE support and Sring framework support.

2, Kotlin for Android development

Android Studio support. Plenty of actual cases. Plenty of learnable app projects. Compatibility with Java allows to use all existing Android libraries in Kotlin applications.

3. Kotlin for JavaScript

Use the kotlinc-js compiler to convert Kotlin code to JavaScript (code that is not Kotlin or standard library will be ignored when compiling), some standard libraries are provided in Kotlin for JS development, and third-party JS libraries can be used at the same time.

Kotlin Native

Kotlin Native is a technology that compiles Kotlin source code into target platform binary data that does not require any VM support. The compiled binary data can be directly run on the target platform. It mainly includes an LLVM-based back-end compiler and a Kotlin native runtime library. The purpose of designing Kotlin Native is to support programming in non-JVM environments, such as embedded platforms and iOS environments, so that Kotlin can run in non-JVM platform environments.
At present, Kotlin Native mainly provides compilers for three mainstream platforms: Mac, Linux, and Windows. Using this compiler, you can easily compile programs running on Raspberry Pi, iOS, OS X, Windows, and Linux systems.

Of course, readers can learn Kotlin Native through a game source code of Kotlin/Native: https://github.com/jetbrains/kotlinconf-spinner

learning materials

Of course, readers can also use the following links to learn Kotlin-related knowledge.
1. Kotlin official website
http://kotlinlang.org/

2.kotlin Chinese official website
https://www.kotlincn.net/

3. Google Kotlin project learning example

https://developer.android.com/samples/index.html?language=kotlin

4. Other articles

https://blog.csdn.net/u013448469/article/details/79403284 Kotlin Reflection

https://blog.csdn.net/ztguang/article/details/72511994 Kotlin Native

5. Video application project
https://github.com/xiangzhihong/EyeVideoClient

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325766297&siteId=291194637