An overview of the

Now Kotlin has started using many open source projects. If you don’t learn, you won’t understand open source. Start learning

Variable definitions

Mutable variable definition

varVariable name: Variable type = variable valuevar name :String = "Xiao Ming"

// Equivalent to Java

String name = "Xiao Ming"

var name = "Xiao Ming" // The compiler automatically pushes the type to String


// Only local variables
var aa : String // Do not initialize the first definition, must have a type
aa = "aa"


Copy the code

Immutable variable definition

valVariable name: Variable type = variable valuevalName: String ="Little red"The equivalent of Javafinal String name = "Little red"
Copy the code

The function definitions

The function defines the keyword fun, and the parameter format is value: type,

The overall format isfunThe method name(Parameter name: Parameter type...): Return value type {method body}fun sum(a: Int, b: Int): Int {
   return a+b
}

Copy the code

The expression is the function body, and the return type is automatically inferred

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

A function that returns no value, similar to void in Java

fun printMsg (msg : Int):Unit {
    print(msg)
}

// No return value can be omitted
fun printMsg1 (msg : Int) {
    print(msg)
}
Copy the code

Variable length parameter

fun aa (vararg a: Int){
    for (v in a){
        print(v)
    }
}

/ / call
fun  main(a){
    aa(1.2.3.4.5)}Copy the code

Lambda (anonymous function)

fun bb(a) {
    val sunLambda: (a: Int, b: Int) - >Int = { x, y -> x + y }
    print(sunLambda(1.2))}/ / call
fun main(a){bb()} this will be detailed laterCopy the code

String template

${method} returns the value of the method as follows:

var a =1

var ss = "value = $a"

var sss = "value =  ${sum(3.4)} "
Copy the code

The output

value = 1
value = 7
Copy the code

NULL checking mechanism

Kotlin has added NullPointerException to the Java system. If we pass a parameter, we need to check whether it is null. Otherwise, NullPointerException will be reported.

public void text(String msg){
        if(msg! =null) {char c = msg.charAt(0); }}Copy the code

Added air safety in Kotlin

// Variables defined in this way are non-null by default
var a1 : String = "123"
// Assigning null to this variable will cause an error
var a1 : String = null
// Add? To the type Operator to indicate that the variable can be null and assigning a value to null will not raise an error
var a2 :String?  = null
Copy the code

How is empty security invoked in code

// By default, the variable's method is not null and can be called arbitrarily
var a1 : String = "123"
a1.length
// Call the variable method directly when it can be null
var a2 :String?  = "123"
a2.length// Compile error
Copy the code

Nullable variables can be called in the following ways

  • The display is interpreted in the code
      val b: String? = "Kotlin"
      if(b ! =null && b.length > 0) {
          print("String of length ${b.length}")}else {
          print("Empty string")}Copy the code
  • use? .The operator
      // the length of a2 is returned if a2 is not null, or null if a2 is null
      var length :Int? = a2? .lengthCopy the code
  • use!!!!!The operator
    // Return normal if it is not null, throw a null pointer exception if it is null
    var length1 : Int= a2!! .lengthCopy the code
  • Elvis operator
      // if a2 is not empty, go? : Left, if empty, go? To the right:
      var length2: Int= a2? .length ? : -1
    Copy the code

Type detection and automatic type conversion

We can use the IS operator to determine that the type is equivalent to instanceof in Java

 if (aa is String){
        // The type is automatically converted to String
        println(aa.length)
    }
/ / or
 if (aa !is String){
        return
    }
    // This will automatically convert String
    println(aa.length)
Copy the code

interval

Kotlin can be accessed via the rangeTo() function in the kotlin.ranges package and its operator form.. Create a range of two values. Usually rangeTo will assist with in and! in

   var i= 1
    if (i in 1.4.) {1<= I <=4
        println(i)
    }

    for (j in 1.4.) {// output 1,2,3,4
        println(j)
    }
Copy the code

Reverse iteration number

    for (k in 4 downTo 1) {// output 4,3,2,1
        println(k)
    }
Copy the code

Customize the iteration step

// Output each time
 for (l in 1.. 5 step 2) {// output 1,3,5
        println(l)
    }
Copy the code

Iteration does not contain an end interval

for (g in 1 until 4) {// Output 1, 2, and 3 do not contain 4
        println(g)
    }
Copy the code

Basic data types

Note only the differences with Java

Type conversion

Because of the different expressions, a smaller type is not a subclass of a larger type and therefore cannot be converted implicitly

var d : Byte = 1

// This will generate an error
var e :Int =d

// This can be used to convert
var f :Int =d.toInt()
Copy the code

Some common conversion methods

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

There are situations that can be automatically converted

var l = 1L+4 //Long + Int = "Long"
Copy the code

An operator

No special characters are used for bit-operations, but only infixes can be used to call named functions, for example

val x = (1 shl 2) and 0x000FF000
Copy the code

This is the complete list of bit operations (for Int Long only)

SHL (bits) - Signed left shift SHR (bits) - Signed right shift USHR (bits) - Unsigned right shift AND (bits) - Bit and OR (bits) - Bit or XOR (bits) - Bit xOR or INV () - bit nonCopy the code

An array of

Arrays are represented as arrays in Kotlin, which defines the get set function (which is converted to []), and the size property

    // define an array [1,2,3]
    var array  = arrayOf(1.2.3)


    // define array [0,2,4]
    var array1 = Array(3,{i->i*2})

    // Create an empty Int array of capacity 6
    var arrayOfNulls = arrayOfNulls<Int> (6)

    array.forEach {
        it->
        println(it)
    }

    array1.forEach {
        println(it)
    }

    arrayOfNulls.forEach {
        println(it)
    }
Copy the code

Arrays in Kotlin are immutable, which means we cannot assign Array

to Array

to prevent possible runtime failures (but you can use Array, see Type projection, generics).

Primitive array

Ktlion also has arrays dedicated to representing primitive data types with no boxing overhead, ByteArray, ShortArray, and IntArra. These are not inherited from the Array class, but they share the same set of methods that are used in the same way as Array

string

Kotlin supports multi-line strings, denoted by “”

// The output will be blank
var text1 = "" multi-line string Multi-line string multi-line string

/ / and can remove the Spaces with trimMargin | as boundary prefix
var text1 = "" "line | more | | multi-line string string multi-line string "" ".trimMargin()
Copy the code

The output

Multi-line string Multi-line string Multi-line string Multi-line string Multi-line string Multi-line stringCopy the code

String template

String literals can contain template expressions, which are little bits of code that evaluate and merge into strings. Template expressions can start with $

val i = 10
println("i = $i") // output "I = 10"
Copy the code
val s = "abc"
println("$s.length is ${s.length}") Abc.length is 3
Copy the code

Both raw and transferred strings support templates. If you need to use the $sign in template strings, you can use the syntax

val price = "" "The ${'$'}9.99 "" "
Copy the code

Under controlled conditions

If expression

  // Common use
    if (a > b) max = a
    
    // Use with else
    if (a > b) {
        max = a
    } else {
        max = b
    }
    
    // If expression returns value Returns value
    var min  = if (a>b) b else a
Copy the code

The basic usage is similar to that of Java, but note that Kotlin’s If expression returns a value, as shown in the third example, which replaces a Java ternary expression

Using interval

if (a in 0.3.){
        println(a)
    }
Copy the code

It can determine whether variable A is 0.. 3 interval

when

This is normal use, equivalent to switch in Java, else equivalent to Defult

 when (a) {
        1 -> println("Enter 1")
        2 -> println("Type 2")
        else -> println("Not 12")}Copy the code

Multiple conditions can also be placed in a branch

 when(a){
       1.2-> println("Input 12")
       else-> println("Not 12")}Copy the code

You can also tell if it’s in an interval or a set

  var items = setOf<Int> (1.2.11)
    when(a){
        in 0.10. -> println("Between 0 and 10.")
        in items-> println("In the set")
        else-> println("Not in the interval.")}Copy the code

It can determine the type, it has a return value, it can be the return value of a method

fun text(a : Any)= when(a){
    is String -> true
    else -> false
}
Copy the code

You can also replace simple if expressions

when {
    x.isOdd() -> print("x is odd")
    y.isEven() -> print("y is even")
    else -> print("x+y is odd.")}Copy the code

The For loop

The for loop can iterate over any iterator provided by the following syntax

for (item in collection) print(item)
Copy the code

For can loop over any object that provides an iterator. That is:

  • There is a member function or extension function iterator() whose return type
  • There is a member function or extension function next(), and
  • There is a member function or extension function hasNext() that returns Boolean.

Ordinary traversal

 for (a in array){
        println(a)
    }
Copy the code

Traversal by index

for (a in array.indices){
        println(array[a])
    }
Copy the code

I’m going to iterate withIndex

for ((index,value) in array.withIndex()){
        println("the element at $index is $value")}Copy the code

Traverse range

  for (a in 1.4.){
        println(a)
    }

    for (a in 6 downTo 0 step 2){
        println(a)
    }
Copy the code

The while loop is the same as Java

Return and jump

The label

The tag is used to specify where to jump, and you can customize the jump with the break continue,return

Definition tags

  • Declaration tag: loop@
  • Use the tag @loop

Use with continue

fun text1(a) {
    for (i in 1.3.) {
        for (j in 1.3.) {
            if (i == 2 && j == 2) {
                continue
            }
            println("$i -> $j")}}}Copy the code

The output

1 -> 1
1 -> 2
1 -> 3
2 -> 1
2 -> 3
3 -> 1
3 -> 2
3 -> 3
Copy the code

Label modification

fun text2(a) {
    look@ for (i in 1.3.) {
        for (j in 1.3.) {
            if (i == 2 && j == 2) {
                continue@look
            }
            println("$i -> $j")}}}Copy the code

The output

1 -> 1
1 -> 2
1 -> 3
2 -> 1
3 -> 1
3 -> 2
3 -> 3
Copy the code

No label out of the internal cycle, the label out of the most external cycle

Use with break

Before modification

fun text3 (a){
    for (i in 1.3.) {
        for (j in 1.3.) {
            if (i == 2 && j == 2) {
                break
            }
            println("$i -> $j")}}}Copy the code

The output

1 -> 1
1 -> 2
1 -> 3
2 -> 1
3 -> 1
3 -> 2
3 -> 3
Copy the code

After transforming

1 -> 1
1 -> 2
1 -> 3
2 -> 1
Copy the code

Before the transformation out of the internal cycle, after the transformation out of the external warm

Use with return

Before the retrofitting

fun text5(a) {
    var arr = arrayOf(1.2.3.0.4.5.6)

    arr.forEach {
        if (it == 0) return
        println(it)
    }
}
Copy the code

The output

1
2
3
Copy the code

After the modification

fun text6(a) {
    var arr = arrayOf(1.2.3.0.4.5.6)

    arr.forEach hhh@{
        if (it == 0) return@hhh
        println(it)
    }
}

// Hermitage method
fun text7(a) {
    var arr = arrayOf(1.2.3.0.4.5.6)

    arr.forEach {
        if (it == 0) return@forEach
        println(it)
    }
}

// Lambda method -> equivalent to recursion
fun text8(a){
    var arr = arrayOf(1.2.3.0.4.5.6)

    arr.forEach(fun(value: Int) {
        if (value == 0) return
        println(value)
    })
}
Copy the code

The output

1
2
3
4
5
6
Copy the code

Exit the method without modifying it, exit it after modifying it and continue the loop

Classes and objects

I’m only talking about the differences with Java

The constructor

The Kotlin class has two constructors, a primary constructor and a secondary constructor,

Principal constructor

The main constructor is the part of the class header that follows the class name, and the constructor keyword is constructor

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

Omit the constructor keyword if the main constructor does not have any annotations or visible modifiers

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

The primary constructor cannot contain any code. The initializer can be placed in the init block. The parameters of the primary constructor can be used in the init block, or can be applied to the assignment of a class’s member attributes

// With the keyword constructor
class A constructor(a: String) {
    var a: String = "shsh"
    val b: String = "ccc"
    var c: String
    val d: String

    // Initialize the code block, which can initialize the main constructor
    init {
        c = a
        d = a
        println(a)
    }

    fun text(a :String) {
        println(a)
    }
}

// Without the keyword constructor
class B(b : String){
    var lastName :String  = "hahha"
        get() {
            if (field.equals("hahha")){
                field="333"
            }
            return field
        }
        set(value) {
            if (value.equals("111")){
                    field="222"
            }else{
                field=value
            }
        }

    var hah :String  = "222"
    init {
        println(b)
    }

/ / comment 1
     fun text(a){
        println(b)The main constructor argument cannot be accessed}}Copy the code

The main constructor parameter is not accessible in the method. How can it be accessed? Both of the following are accessible

class C(c: String) {
    var c1 = c;

    fun text(a){
        println(c1)
    }
}

class  D(var d :String){
    fun text(a){
        println(d)
    }
}
Copy the code

Keywords cannot be hidden if the main constructor has modifiers or annotations

class Customer public @Inject constructor(name: String) { / *... * / }
Copy the code

subconstructor

Classes can also declare subconstructors prefixed by the constructor keyword

class E {

    constructor( a1111: String, b: Int) {
            println(a1111+b)
    }
}
Copy the code

If a class has a primary constructor, each secondary constructor needs to delegate to the primary constructor directly, which can be delegated indirectly through other constructors to another constructor of the same class, using the this keyword

class F(a: String) {

    constructor(a: String, b: Int) : this(a) {

    }
    
    constructor(a:String,b: Int,c:Int):this(a,b){
        
    }
}
Copy the code

Note that the init code block is executed before the secondary constructor

If a non-abstract class does not have any primary and secondary constructors, it automatically generates a primary constructor with no arguments. The constructor is public. If you do not want a public constructor, you can create a constructor and define the scope yourself

class DontCreateMe private constructor () { / *... * / }
Copy the code

Create an instance of the class

The difference with Java is that there is no new keyword

class F(a: String) {

    constructor(a: String, b: Int) : this(a) {

    }

    constructor(a:String,b: Int,c:Int) :this(a,b){

    }
}

fun main(a) {

    // There is no new keyword
   var a  = F("11".1)}Copy the code

Property Getters and Setters

The full syntax for declaring an attribute is

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]
Copy the code

These are the Java get and set methods

public class EE {
    
    public String name;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

This is the normal way to write it in Java,kotlin will automatically generate get and set

class FF {
    var name: String = "name"

    var age: String = "age"
        get// Default implementation
        set// Default implementation

}
Copy the code

Of course, kotlin can also customize get and set methods, where the filed field represents the property

class FF {
    var name: String = "name"
        get() = "Return this no matter what you set."



    var age: String = "age"
        get() {
            if (field.equals("18")){
                field="It's nice to be 18."
            }
            return field
        }
}

fun  main(a){
    var f = FF()


    println(f.age)
    f.age="18"
    println(f.age)

    println(f.name)
    f.name="xiaomign"
    println(f.name)

}
Copy the code

This overrides the get method, and when you use a property value you call the GET method, which returns your custom content

age
18It's nice to be old and it returns this whatever you set it to whatever you set it to, okayCopy the code
class FF {
    var name: String = "name"
        // This returns the original value
        get() = field
        set(value) {
            if (value.equals("Xiao Ming")){
                field="Oh, it's Xiaoming!"}}}fun  main(a){
    var f = FF()

    

    println(f.name)
    f.name="Xiao Ming"
    println(f.name)

}
Copy the code

This overrides the set method, which is called automatically when you assign a value to a property

The output

Name is Xiao MingCopy the code

Val is final in Java and cannot be changed, so val has no set method by default because it cannot be changed. We can also add the access modifier privite,public to get set

class C(c: String) {
    var c1 = c
        private set

    fun text(a){
        println(c1)
    }
}
Copy the code

The set for the C1 property is privite, so c1 cannot be re-assigned externally

Compile-time constant

// Go to the top
const val aaa :String  = "aa"
// Equivalent to Java
public static final  String aaa = "aa"
Copy the code

Delay initialization of property variables

Since normal variables have to be initialized in the constructor, which is inconvenient, we can choose delayed initialization using the keyword lateinit

class C(c: String) {

    lateinit var abc: String

}
Copy the code

This allows for delayed initialization

Nested classes

Equivalent to the static inner class in Java, it does not depend on the object of the external class

class outer { / / outside class
    var a: Int = 1

    class Nested { / / nested classes
        fun text(a) = 2}}fun main(a) {
    var a = outer.Nested().text() // Call mode

    println(a)
}
Copy the code

The inner class

The inner class is represented by the inner keyword, and the inner class takes a reference to the outer class, just like normal inner classes in Java

class outer { / / outside class
    private var a111: Int = 1


    class Nested { / / nested classes
        fun text(a) = 2
    }

    inner class inner { / / inner classes
        fun text(a) = a111 // Access external class member variables

        fun text1(a) {
            var out = this@outer// Get the external class object
            println(out.a111)// Access the external class member}}}fun main(a) {
    var a = outer.Nested().text() // Nested class invocation

    println(a)

    var b = outer().inner().text() // Inner class invocation
    var c = outer().inner().text1()
}
Copy the code

Anonymous inner class

interface Face {
    fun tetx(a) :String
}

class outer {
    fun text3 (face: Face){
        var a = face.tetx()
        println(a)
    }
}

fun main(a) {
    / / use
    outer().text3(object : Face{
        override fun tetx(a): String {
            return "Anonymous inner class"}})}Copy the code

In fact, the root Java is similar

Access modifier

A class property modifier that identifies a class’s intrinsic properties

  • Abstract // Abstract class
  • Final // classes are not inheritable
  • Enum // Enumeration class
  • Open // Classes are inheritable. (Classes are final by default and cannot be inherited)
  • Annotation // Annotation class

An access modifier that identifies the scope of access

  • Public // All places are accessible

  • Private // Only this class can be accessed

  • Protected // This class and subclasses are accessible (this does not modify classes, can modify member variables, methods, etc.)

  • Internal // Only this module can be accessed