入坑Kotlin之流程控制和运算符

if的使用

fun ifExpression(): Int{
    //1.最普通的写法
    var max: Int
    if (a < b) {
        max = b
    }
    else{
        max = a
    }
    return max
}
val max = if(a > b) a else b

如果if语句下由多个语句,那么最后一行是其结果


    val max2 = if(a > b){
        println("a > b")
        a
    }else{
        println("a < b")
        b
    }

when表达式

普通的写法

fun whenExpression(x: Int) {
    when(x){
      1 -> println("x == 1")
      2 -> println("x == 2")
        else -> {
            print("x is neither 1 nor 2")
        }
    }
}

多个case有同一种处理方式的话,可以通过逗号连接

  when(x){
        1, 2 -> println("x == 1 or x == 2")
        else ->  println("x is neither 1 nor 2")
    }

如果case在一定的范围内有相同的处理方式

 when(x){
        in 1..10 -> println("x在1到10的范围内")
        !in 10..20 -> println("x不在10到20的范围内")
        else -> println("none of the above")
    }

如果case是一个表达式,可以这么写

 when(x){
        parseInt(s) -> println("s encodes x")
        else -> println("s does not encode x")
    }

for循环

for循环遍历范围内的数

    for(i in 1..10) println(i)

downTo 从6降到0 step 步长为2

    for(i in 6 downTo 0 step 2) println(i)

for循环遍历一个数组

   var array: Array<String> = arrayOf("I","am","jason","king")
    //迭代一个数组
    for(i in array.indices){
        print(array[i])
    }

遍历数组,输出对应下标的值

    for((index,value) in array.withIndex()){
        println("该数组下标$index 的元素是这个$value")
    }

while循环

while循环的使用有while 和 do-while两种方式

fun whileLoop() {
    var x = 5
    //while
    while (x > 0){
        x--
        print("$x-->")
    }

    x = 5
    println()
    do {
        x--
        print("$x-->")
    } while (x >= 0) // y is visible here!
    
}

流程控制部分的详细内容可以传送到官方文档
Control Flow

运算符重载

Kotlin中任何类可以定义或重载父类的基本运算符,需要用operator关键字

举个栗子,对Complex类重载 + 运算符

class Complex(var real: Double,var imaginary: Double){
    //重载加法运算符
    operator fun plus(other: Complex): Complex {
        return Complex(real + other.real,imaginary + other.imaginary)
    }
    
    //重写toString输出
    override fun toString(): String {
        return "$real + $imaginary"
    }
}

在main函数使用重载的 + 运算符

var c1 = Complex(1.0,2.0)
var c2 = Complex(2.0,3.0)
println(c1 + c2)

输出结果

3.0 + 5.0

运算符部分的详细内容可以传送到官方文档

Operator overloading

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章