Kotlin与Java写法的变更

目录

[获取类的Java Class属性](#获取类的Java Class属性)

类型检查

for循环

switch语句

if判断


获取类的Java Class属性

java 复制代码
//Java
Intent intent = new Intent(this, MainActivity.class);

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

类型检查

java 复制代码
//Java
apple instanceof Fruit
!(apple instanceof Fruit)

//Kotlin
apple is Fruit
apple !is Fruit

for循环

java 复制代码
//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

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中可以这样用:

java 复制代码
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 "其他"
相关推荐
wuminyu5 小时前
JVM规范学习总结:解释器与JIT编译器如何处理JVM字节码
java·linux·c语言·jvm·c++
txxzjmzlh6 小时前
SpringBoot 配置⽂件
java·spring boot·spring
小徐不徐说6 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang6 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
Wang's Blog6 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3276 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
独泪了无痕6 小时前
Hutool之LocalDateTimeUtil:让时间间隔操作如虎添翼
java
Dxy12393102167 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷7 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang8 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain