Kotlin basis

variable

  1. In Kotlin, if is an expression; Assignment operations are expressions in Java, but become statements in Kotlin

    • Expressions differ from statements: Expressions have values and can be used as part of another expression
  2. Variables declared in Kotlin start with the keyword, then the variable name, and finally the type

    • Keyword: val– represents an immutable reference, corresponding to final in Java

      Var — stands for mutable reference

    • Note: Val refers to itself time invariant, but the object it points to can be mutable.
    • If the variable type is not specified, the compiler parses the value of the initializer expression as the type of the variable, or specifies its type explicitly if there is no initializer
  3. String template:Or enclose an expression with ${}

    fun main(args: Array<String>) {
        println("Hello, ${if (args.size > 0) args[0] else "someone"}!")}Copy the code

function

  1. Use the keyword fun to declare functions

  2. Can be defined in the outermost layer of the file, not in a class

  3. Expression body: If a function body is composed of a single expression, the expression can be used as a complete function body

    For example: Yes

  4. Fun Max (a: Int, b: Int): Int {return if (a > b) a else b}Copy the code
  5. // The expression function body
    fun max(a: Int, b: Int):Int = if (a > b) a else b
    Copy the code
  6. // Expression function body + type derivation
    fun max(a: Int, b: Int) = if (a > b) a else b
    Copy the code

class

  1. Arrays are classes

  2. Objects that have only data and no code are called value objects

  3. Properties:

    • When you declare a property, you declare the accessor (read-only properties have only a getter, whereas writable properties have both getters and setters).
    • In Kotlin, you can access properties directly, for exampleperson.isMarried = falseIt’s actually calling the setter
  4. Custom accessors

    class Rectangle(val height: Int.val width: Int) {
        val isSquare: Boolean
            get() {
                return height == width
            }
    }
    Copy the code
  5. The tag class implements the interface, for example:

    class Num(val value: Int) : Expr
    Copy the code

Control structure

  1. Enumeration classes and “when”

    1. whenSimilar to switch in Java but more powerful
  2. Both if and WHEN can use a code block as a branch body, in which case the last expression in the code block is the result

  3. For loop and in

    • Interval: Essentially the interval between two values, one starting and one ending with.. To represent the interval

      • Kotlin’s interval is closed, which means that this second value is always part of the interval

      • // Count backwards from 100 and count only the even numbers
        for (i in 100 downTo 1 step 2) {
            print(fizzBuzz(i))
        }
        Copy the code
      • Use until to indicate semi-closed intervals that do not contain a specified end value

    • Iterative map

      • // Letter represents key, binary represents value, binaryReps represents Map
        for ((letter, binary) in binaryReps) {
            println("$letter = $binary")}Copy the code
      • Map [key] = value; binaryReps[c] = binary; put(c, binary)

      • Use withIndex() to track the index of the current item as it iterates through the collection, without creating a separate variable to store the index and manually incrementing it:

        val list = arrayListOf("1"."11"."111")
        for ((index, element) in list.withIndex()) {
            printlin("$index: $element")}Copy the code
  4. Use in to check the members of collections and intervals

    • inOperator to check if a value is in an interval,! nCheck if the value is not in the interval

Intelligent transformation

  1. isCheck and JavainstanceOfSimilarly, there is no need to explicitly cast a variable after checking that it has a certain type: the compiler uses intelligent conversions
  2. asKeyword to represent a display conversion to a particular type

Exception handling

  1. Don’t have to usenewKeyword to create an exception instance
  2. throwA structure is an expression that can be used as part of another expression
  3. Kotlin does not distinguish between checked and unchecked exceptions, does not specify a function to throw an exception, and may or may not handle an exception

Ps: This article is from: Kotlin In Action

I will update my reading notes every week