[TOC]

preface

In the last section, we focused on Kotlin’s data types. In this section, we mainly understand Kotlin from the perspective of program structure, including methods, class members, and operators

Constants and variables

In the last video we used val and var to decorate properties. In this section, we summarize in detail:

  • Constants (val)
    • Val = value, and value types
    • Java like final
    • It is impossible to duplicate assignments
    • Runtime constants: val x = getX()
    • Compile-time constants: const val x=2

Java final is a runtime constant. Kotlin is a compiler constant.

Java:

public final String S1="A"Public String s2=S1 runtime bytecode: public s2= s2"A"Kotlin: val S1:String="A"Var s2:String =S1: static{s2=S1}Copy the code
  • Variable (var)

    • var = variable
    • Var x =”HelloWorld”// define variables
    • X =”HiWorl”// assign again
  • Type inference The compiler can derive the types of quantities

    • Val string = “Hello”// Deduce the string type
    • Valint = 5 iiint type
    • Var x = getString() + 5 //String
function

A function is a block of code organized with a specific function

  • Fun: [return value type]{[function body]}
  • Fun function name = [expression]

For example:

  • fun sayHi(name: String){ println(“Hi, $name”) }
  • Fun sayHi(name: String) = println(” Hi, $name”)
  • Anonymous functions
    • Fun ([argument list])): [return value type]{[function body]}
      • -val sayHi = fun(name: String) = println(” Hi, $name”)

Java is object oriented, Kotlin is function oriented, functions are first class citizens, in Java you can call an object, you can pass an object around, in Kotlin functions can be done like Java objects, let’s combine the code to experience

fun main(args: Array<String>) {// It is not recommended to use this method to tell whether you want to call a constant or a function. // This is not the same as overloading because val sum =fun is followed by a method with no method name We can use sum.invoke() equivalent to sum() println("Method function" + sum(args[0].toInt(), args[1].toInt()))
    println("Invoke:" + sum(args[0].toInt(), args[1].toInt()))
    println("Constant" + sum.invoke(args[0].toInt(), args[1].toInt()))

}
fun sum(aInt1: Int, aInt2: Int): Int {
    return aInt1 + aInt2
}

val sum = fun(aInt1: Int, aInt2: Int): Int {
    println("$aInt1 + $aInt2 = ${sum(aInt1, aInt2)}")
    return aInt1 + aInt2
}
fun printlnUarge(): String {
    return "Please enter two numerical examples: 1 2"
}

val uager = fun(): String {
    return "Please enter two numerical examples: 1 2"
}
Copy the code
Lambda expressions

Lambda allows functions to be passed as arguments to a method. Lambda expressions can make code much more compact. Java1.8 was added, and Kotlin, a functional programming language, was born with perfect lambda support

  • grammar
(parameters) -> expression
或
(parameters) ->{ statements; }

Copy the code
  • Important features of lambda expressions

    • Optional type declaration: There is no need to declare parameter types, and the compiler can uniformly identify parameter values.
    • Optional parameter parentheses: You do not need to define parentheses for one parameter, but you need to define parentheses for multiple parameters.
    • Optional braces: If the body contains a statement, braces are not required.
    • Optional return keyword: The compiler automatically returns the value if the body has only one expression return value. Curly braces are required to specify that the expression returns a value.

A simple example:

// 1. No arguments, return value 5 () -> 5 // 2. Take an argument (numeric type) and return twice its value x -> 2 * x // 3. Take two arguments (numbers) and return their difference (x, y) -> x -- y // 4. Accept 2 int integers and return their sum (int x, int y) -> x + y Take a string object and print it in the console without returning any value (looks like returning void Unit in Kotlin) (string s) -> system.out.print (s)Copy the code

If Lambda expressions are detailed, it may not be enough to write an article. I think although the code is more concise at the beginning, it is sometimes awkward for me, who only knows Java language, to make a sudden change. I feel that I have to write and read more and gradually adapt to it.

Here I’ll write a few more examples combining the functions and Kotlin features:

fun multiply_1(arg1: Int, arg2: Int): Int {// Lambda: (Int,Int)->Int
    return arg1 * arg2
}

fun multiply_2(arg1: Int, arg2: Int) = arg1 * arg2// Lambda: (Int,Int)->Int

val multiply_3 = { arg1: Int, arg2: Int -> arg1 * arg2 }Lambda: (Int,Int)->Int


val multiply_4 = { arg1: Int, arg2: Int ->
    //lambda
    println("HelloWorld multiply_4")
    println("HelloWorld multiply_4")
    println("HelloWorld multiply_4")
    arg1 * arg2// The last line is the return value of lambda

}
val multiply_5 = fun(arg1: Int, arg2: Int): Int {
    return arg1 * arg2
}Lambda: (Int,Int)->Int
val multiply_6 = {Lambda: ()->Unit
    //lambda
    println("HelloWorld")}fun printlnUsage(a) {Lambda: ()->Unit
    println("no return element")}Lambda: ()->Unit
val sum1 = { it: String ->
    println(it)// Method body content
    Unit// The last line is the return value of lambda Kotlin Unit, equivalent to Java Void with no return value
}

Copy the code

These examples should cover most of the analogies that we’re going to use.

  • Looping statements Kotlin’s looping statements are a bit special look at the following example:
//args=a b c d e f
fun main(args: Array<String>) {

    for (i in args) {
        println(i)
    }
    args.forEach{
        if (it == "d") return
        println(it)
    }
    println("The End")}Copy the code

When you call The second loop, if you want to get out of The loop, then println(“The End”) doesn’t execute. {}} is an expression, not a function.

Args. ForEach Continue@/* Args. ForEach Continue@/* Args.if (it == "d") return@Continue
            println(it)
        }

    }
    println("The End")
Copy the code

Add the flag return@Continue is equivalent to Java Continuereturn@Break is equivalent to Java break. (The definition of the logo is arbitrary, @a@abc can be used)

Member methods and member variables

Here’s a quick example:

Class X class B {// lateinit var a:Int //error // lateinit var a:Double//error // lateinit var a1:Long//error // lateinit var a2:Float//error // lateinit var a3:Short//error // lateinit var a4:Char//error // Lateinit var a5:Byte//error // lateinit var b: Boolean//error var a: Int = 0 get() = field// The default value can not be writtensetField = value} lateinit var c: String lateinit var x1: X // lateinit val x2: Val x2: X by lazy {X()} var cc: String? = null funvalue() {

    }
}

fun main(args: Array<String>) {

    val b = B()
    b.value()
    b.a
}
Copy the code

Let’s summarize the above code directly:

  • Var /val a: Int = 0 The default access modifier is public. It also defaults to getters and setters, but we can override those methods
  • The Backing field property (also called a Backing field) is only available in getters and setters
  • Kotlin suggests that val/var attributes should be initialized directly or in a constructor, and if not degraded to local variables **
  • Lateinit delay initialization. Val cannot be modified. Primitive data types cannot be modified (because primitive data types have default values)
  • Val can be modified by lazy{}

conclusion

I don’t want to be too long, so I’ll continue with the program structure in the next chapter

Github source directly run, including all detailed notes