高级Kotlin强化实战(二)
-
-
-
- [2.Kotlin 与 Java 比较](#2.Kotlin 与 Java 比较)
-
-
2.Kotlin 与 Java 比较
2.5 字符串拼接
java
//Java
String firstName = "Android";
String lastName = "enginner";
String message = "My name is: " + firstName + " " + lastName;
kotlin
//Kotlin
val firstName = "Android"
val lastName = "enginner"
val message = "My name is: $firstName $lastName"
2.6 三元表达式
java
//Java
String text = x > 5 ? "x > 5" : "x <= 5";
kotlin
//kotlin
val text = if (x > 5)
"x > 5"
else
"x <= 5"
2.7 多重条件
java
//Java
if (score >= 0 && score <= 300) { }
java
//kotlin
if (score in 0..300) { }
2.8 更灵活的 case 语句
java
//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
//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
//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
//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
//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
//kotlin
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Android",
2 to "Ali",
3 to "Mindorks")
2.11 遍历
java
// 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
//kotlin
cars.forEach {
println(it.speed)
}
cars.filter { it.speed > 100 }
.forEach { println(it.speed)}
2.12 方法定义
java
//Java
void doSomething() {
// logic here
}
void doSomething(int... numbers) {
// logic here
}
复制
kotlin
//kotlin
fun doSomething() {
// logic here
}
fun doSomething(vararg numbers: Int) {
// logic here
}