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 "其他"
相关推荐
清水白石0081 小时前
Python 编程实战全景:从基础语法到插件架构、异步性能与工程最佳实践
开发语言·python·架构
yaoxin5211232 小时前
390. Java IO API - WatchDir 示例
java·前端·python
Halo_tjn3 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色3 小时前
java 利用redis来限制用户频繁点击
java·开发语言
报错小能手3 小时前
Swift 并发 Combine响应式框架
开发语言·ios·swift
万法若空4 小时前
C++ <memory> 库全方位详解
开发语言·c++
代码中介商4 小时前
C++ 类型转换深度解析:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
青小莫4 小时前
C++之string(OJ练习)
开发语言·c++·stl
freshman_y4 小时前
一篇介绍C语言中二级指针和二维数组的文章
c语言·开发语言
-Marks-4 小时前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本