移动端六大语言速记:第2部分 - 控制结构
本文继续对比Java、Kotlin、Flutter(Dart)、Python、ArkTS和Swift这六种移动端开发语言的控制结构,帮助开发者快速掌握各语言的语法差异。
2. 控制结构
2.1 条件语句
各语言条件语句的语法对比:
语言 | if语句 | 三元运算符 | switch/case | 空值处理 |
---|---|---|---|---|
Java | if (condition) {...} else if (condition) {...} else {...} | condition ? value1 : value2 | switch(var){case val: ... break;} | if(obj != null) |
Kotlin | if (condition) {...} else if (condition) {...} else {...} | if (condition) value1 else value2 | when(var){value -> ...} | ?. , ?: , !! |
Dart | if (condition) {...} else if (condition) {...} else {...} | condition ? value1 : value2 | switch(var){case val: ... break;} | ?. , ?? , !. |
Python | if condition: ... elif condition: ... else: ... | value1 if condition else value2 | 无原生支持,用字典或if-elif | if obj is not None |
ArkTS | if (condition) {...} else if (condition) {...} else {...} | condition ? value1 : value2 | switch(var){case val: ...} | ?. , ?? |
Swift | if condition {...} else if condition {...} else {...} | condition ? value1 : value2 | switch var {case val: ...} | ? , ?? , ! |
示例对比
Java:
// if-else语句
int score = 85;
String grade;if (score >= 90) {grade = "A";
} else if (score >= 80) {grade = "B";
} else if (score >= 70) {grade = "C";
} else {grade = "D";
}// 三元运算符
boolean isPassed = score >= 60 ? true : false;// switch语句
int day = 3;
String dayName;switch (day) {case 1:dayName = "Monday";break;case 2:dayName = "Tuesday";break;case 3:dayName = "Wednesday";break;// ... 其他情况default:dayName = "Invalid day";
}// 空值处理
String text = null;
if (text != null) {System.out.println(text.length());
}
Kotlin:
// if-else语句
val score = 85
val grade = if (score >= 90) {"A"
} else if (score >= 80) {"B"
} else if (score >= 70) {"C"
} else {"D"
}// Kotlin使用if-else作为表达式
val isPassed = if (score >= 60) true else false// when语句 (类似switch)
val day = 3
val dayName = when (day) {1 -> "Monday"2 -> "Tuesday"3 -> "Wednesday"// ... 其他情况else -> "Invalid day"
}// 空值处理
val text: String? = null
// 安全调用操作符
val length = text?.length // 如果text为null,则length为null
// Elvis操作符
val nonNullLength = text?.length ?: 0 // 如果text为null,则nonNullLength为0
// 非空断言操作符
try {val forcedLength = text!!.length // 如果text为null,抛出NullPointerException
} catch (e: Exception) {println("Caught exception: $e")
}
Dart:
// if-else语句
int score = 85;
String grade;if (score >= 90) {grade = "A";
} else if (score >= 80) {grade = "B";
} else if (score >= 70) {grade = "C";
} else {grade = "D";
}// 三元运算符
bool isPassed = score >= 60 ? true : false;// switch语句
int day = 3;
String dayName;switch (day) {case 1:dayName = "Monday";break;case 2:dayName = "Tuesday";break;case 3:dayName = "Wednesday";break;// ... 其他情况default:dayName = "Invalid day";
}// 空值处理
String? text = null;
// 安全调用操作符
int? length = text?.length; // 如果text为null,则length为null
// 空值合并操作符
int nonNullLength = text?.length ?? 0; // 如果text为null,则nonNullLength为0
Python:
# if-else语句
score = 85if score >= 90:grade = "A"
elif score >= 80:grade = "B"
elif score >= 70:grade = "C"
else:grade = "D"# 条件表达式(类似三元运算符)
is_passed = True if score >= 60 else False# 使用字典模拟switch语句
day = 3
day_names = {1: "Monday",2: "Tuesday",3: "Wednesday",# ... 其他情况
}
day_name = day_names.get(day, "Invalid day")# 空值处理
text = None
if text is not None:print(len(text))
ArkTS:
// if-else语句
let score: number = 85;
let grade: string;if (score >= 90) {grade = "A";
} else if (score >= 80) {grade = "B";
} else if (score >= 70) {grade = "C";
} else {grade = "D";
}// 三元运算符
let isPassed: boolean = score >= 60 ? true : false;// switch语句
let day: number = 3;
let dayName: string;switch (day) {case 1:dayName = "Monday";break;case 2:dayName = "Tuesday";break;case 3:dayName = "Wednesday";break;// ... 其他情况default:dayName = "Invalid day";
}// 空值处理
let text: string | null = null;
// 可选链操作符
let length = text?.length; // 如果text为null,则length为undefined
// 空值合并操作符
let nonNullLength = text?.length ?? 0; // 如果text为null,则nonNullLength为0
Swift:
// if-else语句
let score = 85
var grade: Stringif score >= 90 {grade = "A"
} else if score >= 80 {grade = "B"
} else if score >= 70 {grade = "C"
} else {grade = "D"
}// 三元运算符
let isPassed = score >= 60 ? true : false// switch语句
let day = 3
var dayName: Stringswitch day {case 1:dayName = "Monday"case 2:dayName = "Tuesday"case 3:dayName = "Wednesday"// ... 其他情况default:dayName = "Invalid day"
}
// Swift的switch不需要break语句,默认不会贯穿到下一个case// 空值处理
let text: String? = nil
// 可选绑定
if let safeText = text {print(safeText.count)
}
// 空合运算符
let nonNullLength = text?.count ?? 0 // 如果text为nil,则nonNullLength为0
2.2 循环语句
各语言循环语句的语法对比:
语言 | for循环 | while循环 | do-while循环 | 迭代器/集合遍历 |
---|---|---|---|---|
Java | for(init;condition;update) | while(condition) | do {...} while(condition); | for(Type item : collection) |
Kotlin | for(i in range) | while(condition) | do {...} while(condition) | for(item in collection) |
Dart | for(init;condition;update) | while(condition) | do {...} while(condition); | for(var item in collection) |
Python | for i in range() | while condition: | 无原生支持 | for item in collection: |
ArkTS | for(init;condition;update) | while(condition) | do {...} while(condition); | for(let item of collection) |
Swift | for i in range | while condition | repeat {...} while condition | for item in collection |
示例对比
Java:
// 标准for循环
for (int i = 0; i < 5; i++) {System.out.println(i);
}// while循环
int j = 0;
while (j < 5) {System.out.println(j);j++;
}// do-while循环
int k = 0;
do {System.out.println(k);k++;
} while (k < 5);// 增强for循环(集合遍历)
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
for (String fruit : fruits) {System.out.println(fruit);
}
Kotlin:
// 范围for循环
for (i in 0 until 5) {println(i)
}// 步长for循环
for (i in 0..10 step 2) {println(i) // 输出0, 2, 4, 6, 8, 10
}// 倒序for循环
for (i in 5 downTo 1) {println(i) // 输出5, 4, 3, 2, 1
}// while循环
var j = 0
while (j < 5) {println(j)j++
}// do-while循环
var k = 0
do {println(k)k++
} while (k < 5)// 集合遍历
val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {println(fruit)
}// 带索引的集合遍历
for ((index, fruit) in fruits.withIndex()) {println("$index: $fruit")
}
Dart:
// 标准for循环
for (int i = 0; i < 5; i++) {print(i);
}// while循环
int j = 0;
while (j < 5) {print(j);j++;
}// do-while循环
int k = 0;
do {print(k);k++;
} while (k < 5);// 集合遍历
List<String> fruits = ["Apple", "Banana", "Cherry"];
for (var fruit in fruits) {print(fruit);
}// 带索引的集合遍历
for (int i = 0; i < fruits.length; i++) {print("${i}: ${fruits[i]}");
}
Python:
# 范围for循环
for i in range(5):print(i)# 带步长的范围
for i in range(0, 11, 2):print(i) # 输出0, 2, 4, 6, 8, 10# while循环
j = 0
while j < 5:print(j)j += 1# 集合遍历
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:print(fruit)# 带索引的集合遍历
for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")
ArkTS:
// 标准for循环
for (let i = 0; i < 5; i++) {console.log(i);
}// while循环
let j = 0;
while (j < 5) {console.log(j);j++;
}// do-while循环
let k = 0;
do {console.log(k);k++;
} while (k < 5);// 集合遍历
let fruits: string[] = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {console.log(fruit);
}// 带索引的集合遍历
for (let i = 0; i < fruits.length; i++) {console.log(`${i}: ${fruits[i]}`);
}// 使用forEach方法
fruits.forEach((fruit, index) => {console.log(`${index}: ${fruit}`);
});
Swift:
// 范围for循环
for i in 0..<5 {print(i)
}// 步长for循环
for i in stride(from: 0, to: 11, by: 2) {print(i) // 输出0, 2, 4, 6, 8, 10
}// while循环
var j = 0
while j < 5 {print(j)j += 1
}// repeat-while循环 (相当于do-while)
var k = 0
repeat {print(k)k += 1
} while k < 5// 集合遍历
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {print(fruit)
}// 带索引的集合遍历
for (index, fruit) in fruits.enumerated() {print("\(index): \(fruit)")
}
2.3 跳转语句
各语言跳转语句的语法对比:
语言 | break | continue | return | 标签跳转 |
---|---|---|---|---|
Java | break; | continue; | return [value]; | label: for(...) { break label; } |
Kotlin | break | continue | return [value] | @label for(...) { break@label } |
Dart | break; | continue; | return [value]; | label: for(...) { break label; } |
Python | break | continue | return [value] | 无直接支持 |
ArkTS | break; | continue; | return [value]; | label: for(...) { break label; } |
Swift | break | continue | return [value] | label: for {...} break label |
示例对比
Java:
// break语句
for (int i = 0; i < 10; i++) {if (i == 5) {break; // 跳出循环}System.out.println(i); // 输出0, 1, 2, 3, 4
}// continue语句
for (int i = 0; i < 10; i++) {if (i % 2 == 0) {continue; // 跳过当前迭代}System.out.println(i); // 输出1, 3, 5, 7, 9
}// return语句
public int sum(int a, int b) {return a + b; // 返回结果并退出方法
}// 标签跳转
outer: for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (i == 1 && j == 1) {break outer; // 跳出外层循环}System.out.println(i + ", " + j);}
}
Kotlin:
// break语句
for (i in 0 until 10) {if (i == 5) {break // 跳出循环}println(i) // 输出0, 1, 2, 3, 4
}// continue语句
for (i in 0 until 10) {if (i % 2 == 0) {continue // 跳过当前迭代}println(i) // 输出1, 3, 5, 7, 9
}// return语句
fun sum(a: Int, b: Int): Int {return a + b // 返回结果并退出函数
}// 标签跳转
outer@ for (i in 0 until 3) {for (j in 0 until 3) {if (i == 1 && j == 1) {break@outer // 跳出外层循环}println("$i, $j")}
}
Dart:
// break语句
for (int i = 0; i < 10; i++) {if (i == 5) {break; // 跳出循环}print(i); // 输出0, 1, 2, 3, 4
}// continue语句
for (int i = 0; i < 10; i++) {if (i % 2 == 0) {continue; // 跳过当前迭代}print(i); // 输出1, 3, 5, 7, 9
}// return语句
int sum(int a, int b) {return a + b; // 返回结果并退出函数
}// 标签跳转
outer: for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (i == 1 && j == 1) {break outer; // 跳出外层循环}print('$i, $j');}
}
Python:
# break语句
for i in range(10):if i == 5:break # 跳出循环print(i) # 输出0, 1, 2, 3, 4# continue语句
for i in range(10):if i % 2 == 0:continue # 跳过当前迭代print(i) # 输出1, 3, 5, 7, 9# return语句
def sum(a, b):return a + b # 返回结果并退出函数# Python没有直接的标签跳转,但可以用函数或其他方式模拟
def nested_loops():for i in range(3):for j in range(3):if i == 1 and j == 1:return # 使用return退出整个函数print(f"{i}, {j}")nested_loops()
ArkTS:
// break语句
for (let i = 0; i < 10; i++) {if (i == 5) {break; // 跳出循环}console.log(i); // 输出0, 1, 2, 3, 4
}// continue语句
for (let i = 0; i < 10; i++) {if (i % 2 == 0) {continue; // 跳过当前迭代}console.log(i); // 输出1, 3, 5, 7, 9
}// return语句
function sum(a: number, b: number): number {return a + b; // 返回结果并退出函数
}// 标签跳转
outer: for (let i = 0; i < 3; i++) {for (let j = 0; j < 3; j++) {if (i == 1 && j == 1) {break outer; // 跳出外层循环}console.log(`${i}, ${j}`);}
}
Swift:
// break语句
for i in 0..<10 {if i == 5 {break // 跳出循环}print(i) // 输出0, 1, 2, 3, 4
}// continue语句
for i in 0..<10 {if i % 2 == 0 {continue // 跳过当前迭代}print(i) // 输出1, 3, 5, 7, 9
}// return语句
func sum(_ a: Int, _ b: Int) -> Int {return a + b // 返回结果并退出函数
}// 标签跳转
outerLoop: for i in 0..<3 {for j in 0..<3 {if i == 1 && j == 1 {break outerLoop // 跳出外层循环}print("\(i), \(j)")}
}
总结
通过对比六种移动端开发语言的基础语法和控制结构,我们可以发现:
-
语法风格:
- Java和Dart语法相对传统,需要分号结尾
- Kotlin和Swift语法更现代简洁,省略了很多冗余符号
- Python使用缩进表示代码块,语法最为简洁
- ArkTS语法接近TypeScript,结合了静态类型和现代语法特性
-
类型系统:
- Java、Kotlin、Dart、ArkTS和Swift都是静态类型语言
- Python是动态类型语言,不需要显式声明类型
- Kotlin、Dart、ArkTS和Swift都支持类型推断,减少了代码冗余
-
空值处理:
- Kotlin、Dart、ArkTS和Swift都有现代的空值处理机制(如
?.
、??
等) - Java传统上使用null检查,但Java 8+引入了Optional
- Python使用None值和is检查
- Kotlin、Dart、ArkTS和Swift都有现代的空值处理机制(如
-
控制结构:
- 基本控制结构(if-else、循环)在各语言中概念相似但语法有差异
- Kotlin的when和Swift的switch功能更强大,支持更复杂的模式匹配
- Python没有switch语句,通常用字典或if-elif替代
- 各语言的集合遍历语法各有特色,但都支持简洁的迭代方式
理解这些语言间的异同,有助于开发者在不同平台间快速切换,提高跨平台开发效率。在后续文章中,我们将继续探讨这些语言在函数、数据结构、面向对象编程等方面的差异。