您的位置:首页 > 游戏 > 手游 > 如何做到高级Kotlin强化实战?(二)

如何做到高级Kotlin强化实战?(二)

2024/12/31 7:27:10 来源:https://blog.csdn.net/weixin_56715699/article/details/140225865  浏览:    关键词:如何做到高级Kotlin强化实战?(二)

高级Kotlin强化实战(二)

        • 2.Kotlin 与 Java 比较


2.Kotlin 与 Java 比较

2.5 字符串拼接

//Java
String firstName = "Android";
String lastName = "enginner";
String message = "My name is: " + firstName + " " + lastName;
//Kotlin
val firstName = "Android"
val lastName = "enginner"
val message = "My name is: $firstName $lastName"

2.6 三元表达式

//Java
String text = x > 5 ? "x > 5" : "x <= 5";
//kotlin
val text = if (x > 5)
"x > 5"
else
"x <= 5"

2.7 多重条件

//Java
if (score >= 0 && score <= 300) { }
//kotlin
if (score in 0..300) { }

2.8 更灵活的 case 语句

//Java
int score = // some score;
String grade;
switch (score) {
case 10:
case 9:
grade = "Excellent";
break;
case 8:
case 7:
case 6:
grade = "Good";
break;
case 5:
case 4:
grade = "OK";
break;
case 3:
case 2:
case 1:
grade = "Fail";
break;
default:
grade = "Fail";
}
//kotlin
var score = // some score
var grade = when (score) {
9, 10 -> "Excellent"
in 6..8 -> "Good"
4, 5 -> "OK"
in 1..3 -> "Fail"
else -> "Fail"
}

2.9 for 循环

//Java
for (int i = 1; i <= 10 ; i++) { }
for (int i = 1; i < 10 ; i++) { }
for (int i = 10; i >= 0 ; i--) { }
for (int i = 1; i <= 10 ; i+=2) { }
for (int i = 10; i >= 0 ; i-=2) { }
for (String item : collection) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
//kotlin
for (i in 1..10) { }
for (i in 1 until 10) { }
for (i in 10 downTo 0) { }
for (i in 1..10 step 2) { }
for (i in 10 downTo 0 step 2) { }
for (item in collection) { }
for ((key, value) in map) { }

2.10 更方便的集合操作

//Java
final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);
final Map<Integer, String> keyValue = new HashMap<Integer, String>();
map.put(1, "Android");
map.put(2, "Ali");
map.put(3, "Mindorks");
// Java 9
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);
final Map<Integer, String> keyValue = Map.of(1, "Android",
2, "Ali",
3, "Mindorks");
//kotlin
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Android",
2 to "Ali",
3 to "Mindorks")

2.11 遍历

// Java 7 and below
for (Car car : cars) {
System.out.println(car.speed);
}
// Java 8+
cars.forEach(car -> System.out.println(car.speed));
// Java 7 and below
for (Car car : cars) {
if (car.speed > 100) {
System.out.println(car.speed);
}
}
// Java 8+
cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
//kotlin
cars.forEach {
println(it.speed)
}
cars.filter { it.speed > 100 }
.forEach { println(it.speed)}

2.12 方法定义

//Java
void doSomething() {
// logic here
}
void doSomething(int... numbers) {
// logic here
}
复制
//kotlin
fun doSomething() {
// logic here
}
fun doSomething(vararg numbers: Int) {
// logic here
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com