Kotlin与Java写法的变更-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

目录

获取类的Java Class属性

类型检查

for循环

switch语句

if判断


获取类的Java Class属性

//Java
Intent intent = new Intent(this, MainActivity.class);

//Kotlin
val intent = Intent(this, MainActivity::class.java)

类型检查

//Java
apple instanceof Fruit
!(apple instanceof Fruit)

//Kotlin
apple is Fruit
apple !is Fruit

for循环

//Java
List<String> list = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
    //do something
}

//Kotlin 一般写法
for (element in sList) {
    //do something
}

//Kotlin 不需要下标
list.forEach {
    //do something
}

//Kotlin 需要下标
list.forEachIndexed { element, index ->
    //do something
}

switch语句

java

        int status = 0;
        int timeout = 0;
        switch(status){
            case STATUS_1:
                timeout = 100;
                break;
            case STATUS_2:
                timeout = 200;
                break;
            case STATUS_3:
                timeout = 300;
                break;
            default:
                timeout = 500;
                break;
        }

在Kotlin中switch语句正式退出了历史舞台取而代之的是更为强大的when表达式。注意语句statement和表达式expression的区别。通俗来讲他们最大的区别是语句没有值而表达式有值。因此在Kotlin中可以这样用

val status = 0
fun getTime(): Int = when (status) {
    1 -> 100
    2 -> 200
    3 -> 300
    else -> 500
}

if判断

在Kotlin中if变成了表达式等同于 Java中三目运算符的替代写法

fun getStatus(score:Int) = if(score >85) "优秀" else "其他"
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java