Kotlin learning (3) - basic types, packages, control flow: if, when, for, while, Break and continue

1. Basic type

The numerical performance of Kotlin, as follows

  • Double 64
  • Float 32
  • Long 64
  • Int 32
  • Short 16
  • Byte 8

These are all the ways to define numbers, and our general way of writing is similar to JAVA

  • Decimal: 10086
  • Hex: 0x0F
  • Binary: 0b00001011
  • Long type: 10086L
  • Float Type: 10086f
  • Double type: 100.86

At the same time, there is an underscore definition on Kotlin, which can make the code more readable. Let's take a look

fun main(args: Array<String>) {
    val oneMillion = 1_000_000
    val creditCardNumber = 1234_5678_9012_3456L
    val socialSecurityNumber = 999_99_9999L
    val hexBytes = 0xFF_EC_DE_5E
    val bytes = 0b11010010_01101001_10010100_10010010

    print("$oneMillion \n")
    print("$creditCardNumber \n")
    print("$socialSecurityNumber \n")
    print("$hexBytes \n")
    print("$bytes \n")
}

The numbers output by this code

write picture description here

Underscore does not affect our code like JAVA, but makes our code more readable

And in the JAVA platform, the concepts of == and === are similar to == and eques in our JAVA

    val a: Int = 10000
    // true
    print(a === a)
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a
    // false
    print(boxedA === anotherBoxedA)

In this code, we can see that we define an Inta, and define two nullable Ints to assign a value to a, and the result is ===false, but if we
change ==, then the value is equal, == = is the same address, obviously we are two different variables, so false

In addition, in Kotlin, small types are not subclasses of large types, so there is no concept of coercion

such as this wrong example

    val b: Byte = 1 
    val i: Int = b 

This is an implicit conversion, but we can use an explicit conversion to achieve our needs

    val b: Byte = 1
    val i: Int = b.toInt()
    print(i)

Each number can achieve the desired conversion by displaying the conversion

Let's look at logical operations again

  • shl(bits) – signed left shift (<< in Java)
  • shr(bits) – signed right shift (>> in Java)
  • ushr(bits) – signed right shift (>>> in Java)
  • and(bits) – bit AND
  • or(bits) – bit or
  • xor(bits) – bitwise exclusive or
  • inv() – bit not

Let's write an example of a demonstration


    val a: Int = 3
    //<< 1
    print("${a shl 1} \n")
    //>> 1
    print("${a shr 1} \n")
    //>>> 1
    print("${a ushr 1} \n")
    //and 1
    print("and: ${a.and(5)} \n")
    //or  7
    print("or : ${a.or(5)} \n")
    //xor 6 
    print("xor : ${a.xor(5)} \n")
    //inv -4 
    print("inv : ${a.inv()} \n")

Let's take a look at Char, Char cannot exist as a single character or number, and needs to be declared with '' single quotation marks, such as

    var a : Char = '1'

Let's take a look at how to define an array

    //定义items["1","2","3"]
    val items = listOf<String>("1","2","3")
    //指定大小,内容为空
    val itemNulls = arrayOfNulls<Int>(10)
    // 创建⼀个 Array<String> 初始化为 ["0", "1", "4", "9", "16"]
    //val asc = Array(5, { i -> (i * i).toString() })
    // 定义五个数 一直递增
    val asc = Array(5, {i -> (i * i)})

listOf directly declares, arrayOfNulls declares an empty array of fixed length Array defines an array of specified length, value

Look at the string again

    for (c in "Hello") {
        println("$c")
    }

This is our common string, which can contain escapes, and there is also a

    val text = """
        for (c in "foo")
            print(c)
        """

This is a native string, represented by three """. It does not contain escapes. It is what it is. Of course, there are a lot of spaces in this case.

    val text = """
        |for (c in "foo")
            |print(c)
        """.trimMargin()
    print(text)

We can | declare the current start bit, and trimMargin() removes spaces, the result

write picture description here

If you don't handle it like this, your output value will look like this

write picture description here

2. Package

I believe everyone knows the role of the bag


package com.liuguilin.kt_package

fun main(args: Array<String>) {

    print(sum(1,3))
}

fun sum(a: Int, b: Int): Int {
    return a + b;
}

3. Control flow: if, when, for, while

1.if expression

In kotlin, the usage of if is not limited to judgment, it will also return, so we have many ways of writing, such as

    val a = 12;

    //传统
    if (a > 10) {
        print(">")
    } else {
        print("<")
    }

    //表达式
    if (a > 10) print(">") else print("<")

    //表达式
    var b = if (a > 10) 10 else 20

2.When expression

    val today = 4;
    when (today) {
        1 -> print("春季")
        2 -> print("春季")
        3 -> print("春季")
        4 -> print("夏季")
        5 -> print("夏季")
        6 -> print("夏季")
        7 -> print("秋季")
        8 -> print("秋季")
        9 -> print("秋季")
        10 -> print("冬季")
        11 -> print("冬季")
        12 -> print("冬季")
    }

But we generally need an else ending, and we can use in to express

    val today = 4;
    when (today) {
        in 1..3 -> print("春季")
        in 4..6 -> print("夏季")
        in 7..9 -> print("秋季")
        in 10..12 -> print("冬季")
        else -> print("error")
    }

Of course, you can also use is to determine the type, so I won't talk about it here.

3. For loop

    var items = listOf(1,2,3);

    //out 123
    for(a in items) print(a)

    //out 012
    for (a in items.indices) print(a)

    //out 0 , 1  1 , 2  2 , 3
    for ((a,b)in items.withIndex()) print("$a , $b \n")

4.While loop

    var a = 5;

    while (a > 3){
        print(a)
        a--;
    }

    do {
        print(a)
        a--;
    }while (a > 3)

4.Break and continue

Kotlin has three structured jump expressions:

  • return. Defaults to returning from the function or anonymous function that most directly surrounds it.
  • break. Terminate the loop that most directly surrounds it.
  • continue. Continue with the next loop that most directly surrounds it.

Let's look at an example

    var items = listOf(1, 3, 5, 7, 9)

    for (a in items) {
        if (a == 5) {
            continue | break | return
        }
        print("$a \n")
    }

Here, an array is looped. If it is equal to 5, continue, break, and return are executed respectively. If it is break, return will jump out of the loop, which will
only print 1, 3 and continue will jump out of this loop, and will also print 1, 3, 7,9

If you are interested, you can come to Github to participate

My public number, looking forward to your attention

weixin

Guess you like

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