Kotlin艺术探索之流程控制和运算符

if的使用

if-else表达式的使用,最普通的写法如下


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

在Kotlin可以将上面的栗子写成if表达式的形式

val max = if(a > b) a else b
复制代码

注意:表达式一定要完整,不能省略else部分

如果if表达式某个条件下有多个语句,那么最后一行是其返回结果


    val max2 = if(a > b){
        println("a > b")
        a
    }else{
        println("a < b")
        b
    }
复制代码

when表达式

when和java中的switch功能是一样的,switch能实现的,when都可以实现,并且写起来更简洁

when表达式的普通的写法,举个栗子

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

when下的语句,如果其中一条符合条件,就会直接跳出并返回结果

如果多个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!
    
}
复制代码

跳出循环break和跳过循环continue和其他语言语法完全一样,这里就不赘述了。

流程控制部分的详细内容传送到这里

Control Flow 流程控制部分的详细内容可以传送到官方文档 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

猜你喜欢

转载自blog.csdn.net/weixin_33885676/article/details/91388200