Here’s a story:

Let’s start with a story: in the evil old society, young Gu was forced by his parents (market) to take Oracle’s daughter Java as his wife. Marriage is not sweet but still respectful. Not a few years later, Gu mou in business ascendancy, Java family can not help but envy. Several lawsuits were filed to recover the dowry gu forgot to give in those years. Often make gu mou head big unceasingly, borrow wine to pour sorrow. Until that night under the red light before the corridor, strike after the wine wake up, the hospital is also deep to the night is deep, the moon is quiet and quiet. After just be informed, at that time beautiful woman is JetBrains home little female Kotlin. Gu fell in love with what she saw and couldn’t extricate herself. And JetBrains see Gu feng God handsome lang, and also gu all the shopkeeper shopkeeper shopkeeper (big shopkeeper?) , really the dragon and phoenix among men; I’d love to see that happen. Then, the rumor spread. JetBrains approached Gu and asked him to give Kotlin a name. Gu thought Java one day husband and wife 100 days, although the father-in-law’s cruel also can’t blame her. But dragging Kotlin along would be a joke for the world. A bit of tooth, a cross of heart. In the annual gushi big banquet announced: banquet is wedding, wife is flat wife. People in an uproar, there is joy; There are haters, as well as those who wish they’d made JetBrains sooner. Also be so far, gu jia big house courtyard became J, K 2 huang contend for the big stage…… Author: jun MoXiao links: https://www.zhihu.com/question/25289041/answer/174134423 source: zhihu

On May 18, 2017, Google announced that Kotlin had become a tier 1 language for Android development, and since then Kotlin has officially entered the hearts of many developers. Then why Kotlin? Here’s what the official website explains

compatibility

  1. Kotlin is fully compatible with JDK6, ensuring that Kotlin applications can run on older Android devices without any problems.
  2. Kotlin is compatible with the Android build system, and in the coming Android Studio3.0 preview, there is no need for Kotlin development in the form of plug-ins, and you can achieve one-click Conversion of Java code to Kotlin code.

performance

Kotlin applications run at speeds similar to Java, with very similar bytecode structures. With Kotlin’s support for inline functions, code using lambdas typically runs faster than code written in Java.

interoperability

Kotlin is 100% interoperable with Java, allowing all existing Android libraries to be used in Kotlin applications. Annotation processing is included, so are Data Binding and Butter Knife.

Take up the space

Kotlin has a very compact runtime library that can be further reduced by using ProGuard. In a real application, the Kotlin runtime adds only a few hundred methods and has a.apk file size of 100K or less.

Compilation performance

Kotlin supports efficient incremental compilation, so incremental builds are often as fast or faster than Java for clean builds.

For Kotlin’s basic syntax, just read this one

The function definitions

The function definition uses the keyword fun and the parameter format is: parameter: type

Fun sum(a: Int, b: Int): Int {// Int argument, return value Intreturn a + b
}
Copy the code

When an expression is the body of a function, the return type is automatically determined

fun sum(a: Int, b: Int) = a + b
Copy the code

Pay attention to

Public fun sum(a: Int, b: Int): Int = a + bCopy the code

A function that returns no value (similar to void in Java) :

fun printSum(a: Int, b: Int): Unit { 
    print(a + b)} // If you return Unit, you can omit it (also for public methods) : public funprintSum(a: Int, b: Int) { 
    print(a + b)
}
Copy the code

Constant and variable definitions

  1. Variable variable definition: var keyword
Var < identifier > : < type > = < initial value >Copy the code
  1. Definition of immutable variable: the val keyword, a variable that can only be assigned once (similar to a final variable in Java)
Val < identifier > : < type > = < initialization value >Copy the code

Constants and variables can have no initialized value, but must be initialized before reference. The compiler supports automatic type determination, that is, the declaration can not specify the type, the compiler to determine.

Example:

Val a: Int = 1 val b = 1 Var x = 5 // The system automatically concludes that the variable type is Int x += 1 // The variable can be modifiedCopy the code

annotation

Similar to Java, single-line and multi-line comments are supported, except that block comments in Kotlin allow nesting

// This is a single-line comment /* This is a multi-line block comment. * /Copy the code

String template

VarName represents the variable value ${varname.fun ()} represents the method return value of the variable

Var a = 1 // Simple name in the template: val s1 ="a is $a"A = 2 // Any expression in the template: val s2 ="${s1.replace("is", "was")}, but now is $a"
Copy the code

NULL checking mechanism

Kotlin’s empty safety design for the declaration can be empty parameters, in the use of empty judgment processing, there are two processing methods, after the field plus!! Throw an empty exception, as in Java, followed by? Do not do processing return value null or cooperate? : Short judgment processing

// Type after? Var age: String? ="23"Val ages = age!! .toint () // Returns null val ages1 = age? .toint () // return -1 if age is null val ages2 = age? .toInt() ? 1: -Copy the code

interval

Interval expressions are given by operators of the form.. The rangeTo function is complemented by in and! The in formation. An interval is defined for any comparable type, but for integer primitive types, it has an optimized implementation. Here are some examples of using ranges:

    for (i in1.. 4)print("$i "1 2 3 4 println()for (i in4.. 1)print("$i "4 println()for (i in 4 downTo 1) print("$i "// downTo println() should be used in reverse orderfor (i in1.. 10) {// equal to 1 <= I &&i <= 10 //[1,10]print("$i "} println() // use until to exclude the end elementfor (i in1 until 10) {// equal to 1 <= I &&I < 10 //[1,10]print("$i ")
    }
    println()

    for (i in1.. 4 step 2)print("$i "1 3 println()for (i in 4 downTo 1 step 2) print("$i "2 println()Copy the code

Kotlin basic data type

| | type bit width | | — — — — — — — – | — — — — — : | Double | 64 | Float | | 32 Long | 64 | Int 32 | | Short | | 16 Byte | 8

Compare two numbers

In Kotlin, three equal signs === represent the address of the object being compared, and two == represent the size of two values.

fun main(args: Array<String>) {
    val a: Int = 10000
    println(a === a) // true// Two different objects are created val boxedA: Int? = a val anotherBoxedA: Int? = a // Although boxed, the values are the same, both 10000 println(boxedA === anotherBoxedA) //falsePrintln (boxedA == anotherBoxedA) //true, values equal}Copy the code

Type conversion

Each data type has the following methods that can be converted to other types:

toByte(): Byte
toShort(): Short
toInt(): Int
toLong(): Long
toFloat(): Float
toDouble(): Double
toChar(): Char
Copy the code

Such as:

Val b: Byte = 1 // OK, the literal is static check val I: Int = b.toint () // OKCopy the code

Kotlin conditional control

There are two expressions for conditional control in Kotlin

  1. If expression
  2. When the expression

The use of the if expression

The result of an if expression can be assigned to a variable as follows:

val max = if (a > b) {
    print("Choose a")
    a
} else {
    print("Choose b")
    b
}
Copy the code

So you can write it like this

val c = if (condition) a else b
Copy the code

The use of the when expression

The when expression is similar to the Switch expression in Java, in its simplest form:

when (x) {
    1 -> print("x == 1"2 - >)print("x == 2")
    else-> {// Notice this blockprint("X is not one, x is not two.")}}Copy the code

In the when statement, else is the same as in the default switch statement. If none of the other branches meet the criteria, the else branch will go to the else branch. Of course, if many branches need the same treatment, you can put multiple branch conditions together, separated by commas, for example:

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")}Copy the code

We can also detect a value in (in) or not in (! In) an interval or set:

when (x) {
    in1.. 10 - >print("x is in the range")
    in validNumbers -> print("x is valid")!in10.. 20 - >print("x is outside the range")
    else -> print("none of the above")}Copy the code

Another possibility is to detect whether a value is (is) or not (! Is) a value of a specific type. Note: Thanks to smart conversions, you can access methods and properties of this type without any additional detection.

fun hasPrefix(x: Any) = when(x) {
    is String -> x.startsWith("prefix")
    else -> false
}
Copy the code

Example:

fun main(args: Array<String>) {
    val x = 0
    if (x > 0) {
        println("X" (greater than zero)}else if (x == 0) {
        println("X equals 0")}else {
        println("Less than zero")
    }

    val a = 1
    val b = 2
    val c = if (a >= b) a else b
    println("Has a value of c$c")

    when (x) {
        0, 1 -> println("x==0 or x==1")
        else -> println("otherwise")

    }

    when (x) {
        1 -> println("x==1")
        2 -> println("x==2")
        else -> {
            println("X is not one, x is not two.")
        }
    }

    when (x) {
        in0.. 10 -> println("X is within that range.")
        else -> println("X is not within that range.")}}Copy the code

Kotlin cycle control

Like Java, kotlin loops come in three forms, for loops, while loops, and do…. The while loop. But the usage is a little different.

The for loop

The basic usage is as follows:

for (item: Int inInts) {/ /... }Copy the code

Examples are as follows:

fun main(args: Array<String>) {
    val items = listOf("apple"."banana"."kiwi")
    for (item in items) {
        println(item)
    }

    for (index in items.indices) {
        println("item at $index is ${items[index]}")}}Copy the code

The result is as follows:

apple
banana
kiwi
item at 0 is apple
item at 1 is banana
item at 2 is kiwi
Copy the code

Attention!!!!!

The for loop used in Kotlin is similar to the for loop used in Java, but does not use for(int I =0; i

While loops and do… The while loop

The while loop is the most basic loop. Its basic structure is as follows:

while(Boolean expression) {// loop contents}Copy the code

do… The basic structure of the while loop is:

do{// code statement}while(Boolean expression);Copy the code

While loops and do… The while loop is consistent as follows:

fun main(args: Array<String>) {
    println(- while the use of -- -- -- -- --")
    var x = 5
    while (x > 0) {
        println( x--)
    }
    println("----do... While the use of -- -- -- -- --")
    var y = 5
    do {
        println(y--)
    } while(y>0)
}
Copy the code

Output result:

----while using ----- 5 4 3 2 1 ----do... While using ----- 5 4 3 2 1Copy the code

Loop back and jump

Kotlin has three expressions for structured jumps:

  1. return
  2. break
  3. Continue is understood as it is in Java, and the basic usage is the same, but break and continue have new uses in Kotlin

Break and Continue tags

Any expression in Kotlin can be labeled with a label. Labels are in the format of an identifier followed by an @ sign, such as ABC @ and fooBar@. To label an expression, we simply label it.

loop@ for (i in1.. 100) {for (j in1.. 100) {if(...)break@loop
    }
}
Copy the code

The break restricted by the tag jumps to the execution point just after the loop specified by the tag. Continue continues the next iteration of the loop specified by the tag.

You can specify which loop to exit at what time by specifying the tag

Kotlin classes and objects

The Kotlin class can contain the following things:

  1. Constructor and initialization code block
  2. A member function
  3. attribute
  4. The inner class
  5. Object statement

Kotlin uses the keyword *** *class*** to declare a class, followed by the class name. In a class, you can define member functions in the following format:

Class Temp{// The name of the class is Temp // The body of the class is fun inside the bracesf(){
        println("This is a member function.")}}Copy the code

Attributes of a class

Class attributes are declared mutable with the keyword ***var**, otherwise declared immutable with ***val***

Class Temp{var name: String =...... Var url: String =...... Var city: String =...... }Copy the code

You can also use constructors to create class instances just as you would with normal functions:

Val temp= temp () // There is no new keyword in KotlinCopy the code

To use an attribute, all you need is a name reference

temp.name
temp.url
Copy the code

Note that there is no new keyword in Kotlin, and instantiating an object does not require the new keyword as Java does.

Getter and setter

Getter and setter properties are optional and are used in a similar way to the get and set methods in c#. If the property type can be inferred from an initializer or from a class member function, the type can be omitted

Attention!! Val does not allow setting setter functions because the function is read-only.

var allByDefault: Int? Var Initialized = 1 // The type is Int and the getter and setter are implemented by default. Val simple: Int? Var inferredType = 1; var inferredType = 1; var inferredType = 1Copy the code

The instance

The following example defines a Person class that contains two mutable variables, lastName, which modifies the getter method, and no, which modifies the setter method.

class Person {

    var lastName: String = "zhang"Get () = field.touppercase () // convert the assigned variable toUpperCasesetVar no: Int = 100 get() = fieldset(value) {
            if(value < 10) {// Return the value if the value passed is less than 10 field = value}else{field = -1 // Returns -1 if the value passed is greater than or equal to 10}} var heiht: Float = 145.4f privateset} // Test fun main(args: Array<String>) {var person: person = person () person"wang"

    println("lastName:${person.lastName}")

    person.no = 9
    println("no:${person.no}")

    person.no = 20
    println("no:${person.no}")}Copy the code

The output is:

lastName:WANG
no:9
no:-1
Copy the code

Classes in Kotlin cannot have fields. The Backing Fields mechanism is provided, with backup Fields declared using the field keyword, which can only be used by accessors to properties

Primary and secondary constructors

Classes in Koltin can have a primary constructor and one or more secondary constructors, which are part of the class header and come after the class name:

class Person constructor(firstName: String) {}
Copy the code

If the main constructor does not have any annotations and does not have any visibility modifiers, the constructor keyword can be omitted

class Person(firstName: String) {}
Copy the code

The main constructor

The primary constructor cannot contain any code, and the initialization code can be prefixed with the init keyword in the initialization code snippet

class Person constructor(firstName: String) {
    init {
        System.out.print("FirstName is $firstName")}}Copy the code

Example:

Class Runoob constructor(name: String) {// The class name is Runoob //"http://www.runoob.com"
    var country: String = "CN"
    var siteName = name

    init {
        println("Initialize the site name:${name}")
    }

    fun printTest() {
        println("I'm a function of class.")
    }
}

fun main(args: Array<String>) {
    val runoob =  Runoob("Rookie Tutorial")
    println(runoob.siteName)
    println(runoob.url)
    println(runoob.country)
    runoob.printTest()
}
Copy the code

subconstructor

A class can also have secondary constructors, and can have more than one, prefixed by constructor

class Person { 
    constructor(parent: Person) {
        parent.children.add(this) 
    }
}
Copy the code

If a class has a primary constructor, each subconstructor must, either directly or indirectly, proxy the primary constructor through another subconstructor. Proiding another constructor in the same class using the this keyword:

Class Person(val name: String) {constructor (name: String, age:Int) : this(name) {// Initialize... }}Copy the code

Example:

Class Runoob constructor(name: String) {// The class name is Runoob //"http://www.runoob.com"
    var country: String = "CN"
    var siteName = name

    init {
        println("Initialize the site name:${name}"} // Constructor (name: String, alexa: Int) : this(name) {println();}"Alexa ranking$alexa")
    }

    fun printTest() {
        println("I'm a function of class.")
    }
}

fun main(args: Array<String>) {
    val runoob =  Runoob("Rookie Tutorial", 10000)
    println(runoob.siteName)
    println(runoob.url)
    println(runoob.country)
    runoob.printTest()
}
Copy the code

Kotlin inheritance

All classes in Kotlin inherit from Any, and if a class is to be inherited, it needs to be decorated with the open keyword

Open Class Base(p: Int) // Class Derived(p: Int) : Base(p)Copy the code

The constructor

If a subclass has a primary constructor, the base class must be initialized immediately in the primary constructor

Open class Person(var name: String, var age: Int){// class Student(name: String, age: Int, var no: String, var score: Int) : Person(name, age) {}"Runoob", 18."S12346", 89)
    println("Student name:${s.name}")
    println("Age:${s.age}")
    println("Student Number:${s.no}")
    println("The result:${s.score}")}Copy the code

There is no primary constructor in a subclass

If the subclass does not have a primary constructor, then the base class must be initialized with the super keyword in each secondary constructor, or another constructor must be proxy. When initializing a base class, different constructors of the base class can be called.

Public class Person(name:String){public class Person(name:String){public class Person(name:String){public class Person(name:String,age:Int); public class Person(name:String,age:Int); public class Person(name:String,age:Int); public class Person(name:String,age:Int);"------- base class secondary constructor ---------"Class Student:Person{/** secondary constructor **/ constructor(name:String,age:Int,no:String,score:Int):super(name,age){ println("------- inherits class secondary constructor ---------")
        println("Student name:${name}")
        println("Age:${age}")
        println("Student Number:${no}")
        println("The result:${score}")
    }
}

fun main(args: Array<String>) {
    var s =  Student("Runoob", 18."S12345", 89)}Copy the code

rewrite

If subclass overrides are allowed, then manually add the open modifier and override the method using the override keyword:

/** user base **/ open class Person{open funstudy(){// Allow subclasses to override println()"I graduated."}} /** Subclass Person **/ class Student:Person() {

    override fun study(){// override println()"I'm in college.")
    }
}

fun main(args: Array<String>) {
    val s =  Student()
    s.study();

}
Copy the code

If there are multiple identical methods (inherited or implemented from other classes, such as class A or B), then the method must be overridden to use the super stereotype to selectively call the implementation of the parent class.

open class A {
    open fun f () { print("A") }
    fun a() { print("a") }
}

interface B {
    fun f() { print("B"} // The default member variable of the interface is open funb() { print("b") }
}

class C() : A() , B{
    override fun f() {super < A > f () / / call A.f () super < B > f () / / call b. ()}} fun main (args: Array < String >) {c = c () of the val c.f (); }Copy the code

Kotlin interface

Interfaces in Kotlin are used similarly to java8 in that they are defined with the interface keyword, allowing implementations of default methods.

Methods in interfaces

Example:

interface MyInterface {
    fun bar()
    fun foo() {// Optional method body println()"foo")
    }
}
class Child : MyInterface {
    override fun bar() {// method body println()"bar")
    }
}
fun main(args: Array<String>) {
    val c =  Child()
    c.foo();
    c.bar();
}
Copy the code

Attributes in interfaces

Attributes in an interface can only be abstract and cannot be initialized. The interface does not coarse the attribute values. When implementing the interface, the attribute must be overridden. Example:

Interface MyInterface {var name:String //name, abstract fun bar() funfoo() {// Optional method body println()"foo")
    }
}
class Child : MyInterface {
    override var name: String = "runoob"// Override funbar() {// method body println()"bar")
    }
}
fun main(args: Array<String>) {
    val c =  Child()
    c.foo();
    c.bar();
    println(c.name)
 
}
Copy the code

Function to rewrite

Overwriting a method in an interface is similar to overwriting a method in an inherited class, as shown below:

interface A {
    fun foo() { print("A"} interface B {fun} interface B {fun} interface B {fun} interface B {fun} interface B {funfoo() { print("B"} // Fun is implementedbar() { print("bar"} class C: A {override funbar() { print("bar"Class D: A, B {override funfoo() {
        super<A>.foo()
        super<B>.foo()
    }
 
    override fun bar() {
        super<B>.bar()
    }
}
 
fun main(args: Array<String>) {
    val d =  D()
    d.foo();
    d.bar();
}
Copy the code

Developing IDE: IDEA/Android Studio