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

if的使用

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

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

在Kotlin能够将上面的栗子写成if表达式的形式java

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

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

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

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

when表达式

when和java中的switch功能是同样的,switch能实现的,when均可以实现,而且写起来更简洁ide

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

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

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

若是多个case有同一种处理方式的话,能够经过逗号链接,譬如这样:ui

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

那若是case在必定的范围内有相同的处理方式呢?能够这样写:spa

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

那若是case是一个表达式,就能够这么写:code

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

相关文章
相关标签/搜索