渭南市建设局网站2345网址导航浏览器下载
移动端六大语言速记:第3部分 - 函数与方法
本文对比Java、Kotlin、Flutter(Dart)、Python、ArkTS和Swift这六种移动端开发语言的函数与方法特性,帮助开发者快速掌握各语言的语法差异。
3. 函数与方法
3.1 函数定义与调用
各语言函数定义与调用的语法对比:
语言 | 函数定义 | 方法定义 | 调用方式 | 默认参数 | 命名参数 |
---|---|---|---|---|---|
Java | returnType name(params) {...} | modifier returnType name(params) {...} | name(args) | 不支持 | 不支持 |
Kotlin | fun name(params): ReturnType {...} | fun Class.name(params): ReturnType {...} | name(args) | 支持 | 支持 |
Dart | returnType name(params) {...} | returnType name(params) {...} | name(args) | 支持(命名或位置可选) | 支持 |
Python | def name(params): | def name(self, params): | name(args) | 支持 | 支持 |
ArkTS | function name(params): ReturnType {...} | name(params): ReturnType {...} | name(args) | 支持 | 支持 |
Swift | func name(params) -> ReturnType {...} | func name(params) -> ReturnType {...} | name(args) | 支持 | 支持(必需) |
示例对比
Java:
// 函数定义(在Java中,函数必须在类内部定义,称为方法)
public class Calculator {// 实例方法public int add(int a, int b) {return a + b;}// 静态方法public static int multiply(int a, int b) {return a * b;}
}// 方法调用
Calculator calc = new Calculator();
int sum = calc.add(5, 3); // 实例方法调用
int product = Calculator.multiply(4, 2); // 静态方法调用
Kotlin:
// 顶层函数(不需要类)
fun add(a: Int, b: Int): Int {return a + b
}// 带默认参数的函数
fun greet(name: String = "Guest"): String {return "Hello, $name!"
}// 类中的方法
class Calculator {// 实例方法fun multiply(a: Int, b: Int): Int {return a * b}// 伴生对象中的方法(类似静态方法)companion object {fun divide(a: Int, b: Int): Int {return a / b}}
}// 函数调用
val sum = add(5, 3) // 顶层函数调用
val greeting1 = greet() // 使用默认参数 -> "Hello, Guest!"
val greeting2 = greet("John") // 指定参数 -> "Hello, John!"
val greeting3 = greet(name = "Alice") // 命名参数调用// 方法调用
val calc = Calculator()
val product = calc.multiply(4, 2) // 实例方法调用
val quotient = Calculator.divide(8, 2) // 伴生对象方法调用
Dart:
// 顶层函数
int add(int a, int b) {return a + b;
}// 带可选位置参数的函数
String greet(String name, [String title = "Mr./Ms."]) {return "Hello, $title $name!";
}// 带命名参数的函数
String introduce({required String name, int age = 30, String? occupation}) {var intro = "My name is $name and I am $age years old";if (occupation != null) {intro += ". I work as a $occupation";}return intro;
}// 类中的方法
class Calculator {// 实例方法int multiply(int a, int b) {return a * b;}// 静态方法static int divide(int a, int b) {return a ~/ b; // 整数除法}
}// 函数调用
var sum = add(5, 3); // 顶层函数调用
var greeting1 = greet("John"); // 使用默认参数 -> "Hello, Mr./Ms. John!"
var greeting2 = greet("Jane", "Dr."); // 指定参数 -> "Hello, Dr. Jane!"// 命名参数调用
var intro1 = introduce(name: "Alice"); // 使用默认age,不提供occupation
var intro2 = introduce(name: "Bob", age: 25, occupation: "Developer");// 方法调用
var calc = Calculator();
var product = calc.multiply(4, 2); // 实例方法调用
var quotient = Calculator.divide(8, 2); // 静态方法调用
Python:
# 函数定义
def add(a, b):return a + b# 带默认参数的函数
def greet(name="Guest"):return f"Hello, {name}!"# 带可变参数的函数
def sum_all(*numbers):return sum(numbers)# 带关键字参数的函数
def create_profile(name, **details):profile = {"name": name}profile.update(details)return profile# 类中的方法
class Calculator:# 实例方法def multiply(self, a, b):return a * b# 静态方法@staticmethoddef divide(a, b):return a // b # 整数除法# 函数调用
sum_result = add(5, 3) # 基本调用
greeting1 = greet() # 使用默认参数 -> "Hello, Guest!"
greeting2 = greet("John") # 指定参数 -> "Hello, John!"
greeting3 = greet(name="Alice") # 命名参数调用total = sum_all(1, 2, 3, 4, 5) # 可变参数调用 -> 15# 关键字参数调用
user = create_profile("Bob", age=30, occupation="Developer", location="New York")# 方法调用
calc = Calculator()
product = calc.multiply(4, 2) # 实例方法调用
quotient = Calculator.divide(8, 2) # 静态方法调用
ArkTS:
// 函数定义
function add(a: number, b: number): number {return a + b;
}// 带默认参数的函数
function greet(name: string = "Guest"): string {return `Hello, ${name}!`;
}// 带可选参数的函数
function createUser(name: string, age?: number, isActive: boolean = true): object {return { name, age, isActive };
}// 类中的方法
class Calculator {// 实例方法multiply(a: number, b: number): number {return a * b;}// 静态方法static divide(a: number, b: number): number {return Math.floor(a / b); // 整数除法}
}// 函数调用
let sum = add(5, 3); // 基本调用
let greeting1 = greet(); // 使用默认参数 -> "Hello, Guest!"
let greeting2 = greet("John"); // 指定参数 -> "Hello, John!"// 带可选参数的调用
let user1 = createUser("Alice"); // 只提供必需参数
let user2 = createUser("Bob", 30); // 提供部分可选参数
let user3 = createUser("Charlie", 25, false); // 提供所有参数// 方法调用
let calc = new Calculator();
let product = calc.multiply(4, 2); // 实例方法调用
let quotient = Calculator.divide(8, 2); // 静态方法调用
Swift:
// 函数定义
func add(a: Int, b: Int) -> Int {return a + b
}// 带默认参数的函数
func greet(name: String = "Guest") -> String {return "Hello, \(name)!"
}// 带外部参数名的函数
func calculateArea(of rectangle: (width: Double, height: Double)) -> Double {return rectangle.width * rectangle.height
}// 可变参数函数
func sumAll(_ numbers: Int...) -> Int {return numbers.reduce(0, +)
}// 类中的方法
class Calculator {// 实例方法func multiply(a: Int, b: Int) -> Int {return a * b}// 类方法(静态方法)class func divide(a: Int, b: Int) -> Int {return a / b}
}// 函数调用
let sum = add(a: 5, b: 3) // Swift默认使用参数标签
let greeting1 = greet() // 使用默认参数 -> "Hello, Guest!"
let greeting2 = greet(name: "John") // 指定参数 -> "Hello, John!"// 使用外部参数名
let area = calculateArea(of: (width: 10.0, height: 5.0))// 可变参数调用
let total = sumAll(1, 2, 3, 4, 5) // -> 15// 方法调用
let calc = Calculator()
let product = calc.multiply(a: 4, b: 2) // 实例方法调用
let quotient = Calculator.divide(a: 8, b: 2) // 类方法调用
3.2 参数传递
各语言参数传递机制对比:
语言 | 基本类型传递 | 对象传递 | 可变参数 | 函数参数 |
---|---|---|---|---|
Java | 值传递 | 引用传递 | Type... args | 函数式接口 |
Kotlin | 值传递 | 引用传递 | vararg items: Type | 函数类型 |
Dart | 值传递 | 引用传递 | List<Type> args | 函数对象 |
Python | 对象引用 | 对象引用 | *args | 函数对象 |
ArkTS | 值传递 | 引用传递 | ...args: Type[] | 函数类型 |
Swift | 值传递 | 引用传递 | args: Type... | 函数类型 |
示例对比
Java:
// 基本类型参数(值传递)
public void incrementValue(int x) {x++; // 只在函数内部改变,不影响原始值
}// 对象参数(引用传递)
public void updatePerson(Person person) {person.setName("Updated"); // 修改会影响原始对象
}// 可变参数
public int sum(int... numbers) {int total = 0;for (int num : numbers) {total += num;}return total;
}// 函数参数(使用函数式接口)
public void processWithCallback(Runnable callback) {// 执行一些操作callback.run(); // 调用传入的函数
}// 调用示例
int value = 10;
incrementValue(value); // value仍然是10Person person = new Person("Original");
updatePerson(person); // person.name变为"Updated"int total = sum(1, 2, 3, 4, 5); // 使用可变参数// 使用Lambda作为函数参数
processWithCallback(() -> System.out.println("Callback executed"));
Kotlin:
// 基本类型参数(值传递)
fun incrementValue(x: Int) {var y = xy++ // 只在函数内部改变,不影响原始值
}// 对象参数(引用传递)
fun updatePerson(person: Person) {person.name = "Updated" // 修改会影响原始对象
}// 可变参数
fun sum(vararg numbers: Int): Int {return numbers.sum()
}// 函数参数
fun processWithCallback(callback: () -> Unit) {// 执行一些操作callback() // 调用传入的函数
}// 高阶函数示例
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {return operation(a, b)
}// 调用示例
val value = 10
incrementValue(value) // value仍然是10val person = Person("Original")
updatePerson(person) // person.name变为"Updated"val total = sum(1, 2, 3, 4, 5) // 使用可变参数// 使用Lambda作为函数参数
processWithCallback { println("Callback executed") }// 高阶函数调用
val result1 = operate(10, 5) { a, b -> a + b } // 加法
val result2 = operate(10, 5) { a, b -> a * b } // 乘法
Dart:
// 基本类型参数(值传递)
void incrementValue(int x) {x++; // 只在函数内部改变,不影响原始值
}// 对象参数(引用传递)
void updatePerson(Person person) {person.name = "Updated"; // 修改会影响原始对象
}// 可选位置参数
int sum(int a, int b, [int c = 0, int d = 0]) {return a + b + c + d;
}// 函数参数
void processWithCallback(void Function() callback) {// 执行一些操作callback(); // 调用传入的函数
}// 高阶函数
int operate(int a, int b, int Function(int, int) operation) {return operation(a, b);
}// 调用示例
int value = 10;
incrementValue(value); // value仍然是10Person person = Person("Original");
updatePerson(person); // person.name变为"Updated"int total1 = sum(1, 2); // 使用必需参数
int total2 = sum(1, 2, 3); // 使用部分可选参数
int total3 = sum(1, 2, 3, 4); // 使用所有参数// 使用匿名函数作为参数
processWithCallback(() => print("Callback executed"));// 高阶函数调用
int result1 = operate(10, 5, (a, b) => a + b); // 加法
int result2 = operate(10, 5, (a, b) => a * b); // 乘法
Python:
# 基本类型参数(对象引用)
def increment_value(x):x += 1 # 对于不可变类型,只在函数内部改变,不影响原始值# 对象参数(对象引用)
def update_person(person):person['name'] = "Updated" # 修改会影响原始对象# 可变参数
def sum_values(*numbers):return sum(numbers)# 关键字可变参数
def create_user(name, **properties):user = {'name': name}user.update(properties)return user# 函数参数
def process_with_callback(callback):# 执行一些操作callback() # 调用传入的函数# 高阶函数
def operate(a, b, operation):return operation(a, b)# 调用示例
value = 10
increment_value(value) # value仍然是10(整数是不可变的)list_value = [1, 2, 3]
increment_value(list_value) # list_value变为[1, 2, 3, 1](列表是可变的)person = {'name': 'Original'}
update_person(person) # person['name']变为"Updated"total = sum_values(1, 2, 3, 4, 5) # 使用可变参数# 创建用户,使用关键字可变参数
user = create_user("John", age=30, role="admin", active=True)# 使用Lambda作为函数参数
process_with_callback(lambda: print("Callback executed"))# 高阶函数调用
result1 = operate(10, 5, lambda a, b: a + b) # 加法
result2 = operate(10, 5, lambda a, b: a * b) # 乘法
ArkTS:
// 基本类型参数(值传递)
function incrementValue(x: number): void {x++; // 只在函数内部改变,不影响原始值
}// 对象参数(引用传递)
function updatePerson(person: Person): void {person.name = "Updated"; // 修改会影响原始对象
}// 可选参数
function sum(a: number, b: number, c?: number, d?: number): number {return a + b + (c || 0) + (d || 0);
}// 函数参数
function processWithCallback(callback: () => void): void {// 执行一些操作callback(); // 调用传入的函数
}// 高阶函数
function operate(a: number, b: number, operation: (x: number, y: number) => number): number {return operation(a, b);
}// 调用示例
let value: number = 10;
incrementValue(value); // value仍然是10let person: Person = new Person("Original");
updatePerson(person); // person.name变为"Updated"let total1: number = sum(1, 2); // 使用必需参数
let total2: number = sum(1, 2, 3); // 使用部分可选参数
let total3: number = sum(1, 2, 3, 4); // 使用所有参数// 使用箭头函数作为参数
processWithCallback(() => console.log("Callback executed"));// 高阶函数调用
let result1: number = operate(10, 5, (a, b) => a + b); // 加法
let result2: number = operate(10, 5, (a, b) => a * b); // 乘法
Swift:
// 基本类型参数(值传递)
func incrementValue(_ x: Int) {var y = xy += 1 // 只在函数内部改变,不影响原始值
}// 对象参数(引用传递)
func updatePerson(_ person: Person) {person.name = "Updated" // 修改会影响原始对象
}// 可变参数
func sum(_ numbers: Int...) -> Int {return numbers.reduce(0, +)
}// 函数参数
func processWithCallback(_ callback: () -> Void) {// 执行一些操作callback() // 调用传入的函数
}// 高阶函数
func operate(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int {return operation(a, b)
}// 调用示例
var value = 10
incrementValue(value) // value仍然是10let person = Person(name: "Original")
updatePerson(person) // person.name变为"Updated"let total = sum(1, 2, 3, 4, 5) // 使用可变参数// 使用闭包作为函数参数
processWithCallback { print("Callback executed") }// 高阶函数调用
let result1 = operate(10, 5) { $0 + $1 } // 加法,使用简写参数名
let result2 = operate(10, 5) { a, b in a * b } // 乘法,显式参数名
3.3 返回值
各语言返回值机制对比:
语言 | 单值返回 | 多值返回 | 可空返回 | 返回类型声明 |
---|---|---|---|---|
Java | 支持 | 通过对象/数组/集合 | 可返回null | 必需 |
Kotlin | 支持 | 通过Pair/Triple/数据类 | 通过可空类型 | 可推断 |
Dart | 支持 | 通过List/Map/自定义类 | 可返回null | 可选 |
Python | 支持 | 通过元组/列表/字典 | 可返回None | 可选(类型提示) |
ArkTS | 支持 | 通过数组/对象 | 通过可选类型 | 必需 |
Swift | 支持 | 通过元组 | 通过可选类型 | 可推断 |
示例对比
Java:
// 单值返回
public int square(int x) {return x * x;
}// 多值返回(通过对象)
public class Result {private final int sum;private final int product;public Result(int sum, int product) {this.sum = sum;this.product = product;}public int getSum() { return sum; }public int getProduct() { return product; }
}public Result calculate(int a, int b) {return new Result(a + b, a * b);
}// 可空返回
public String findName(int id) {if (id <= 0) {return null; // 返回null表示未找到}return "User" + id;
}// 调用示例
int area = square(5); // 返回25Result result = calculate(3, 4);
int sum = result.getSum(); // 7
int product = result.getProduct(); // 12String name = findName(-1); // 返回null
if (name != null) {System.out.println(name.length()); // 需要null检查
}
Kotlin:
// 单值返回
fun square(x: Int): Int {return x * x
}// 使用表达式函数体
fun cube(x: Int) = x * x * x// 多值返回(通过Pair)
fun calculate(a: Int, b: Int): Pair<Int, Int> {return Pair(a + b, a * b)
}// 使用数据类返回多个值
data class Result(val sum: Int, val product: Int, val difference: Int)fun calculateExtended(a: Int, b: Int): Result {return Result(a + b, a * b, a - b)
}// 可空返回
fun findName(id: Int): String? {if (id <= 0) {return null // 返回null表示未找到}return "User$id"
}// 调用示例
val area = square(5) // 返回25
val volume = cube(3) // 返回27val (sum, product) = calculate(3, 4) // 解构赋值val result = calculateExtended(3, 4)
val difference = result.difference // 访问数据类属性val name = findName(-1) // 返回null
// 使用安全调用操作符
val length = name?.length // 如果name为null,则length为null
Dart:
// 单值返回
int square(int x) {return x * x;
}// 使用箭头函数
int cube(int x) => x * x * x;// 多值返回(通过List)
List<int> calculate(int a, int b) {return [a + b, a * b];
}// 使用类返回多个值
class Result {final int sum;final int product;final int difference;Result(this.sum, this.product, this.difference);
}Result calculateExtended(int a, int b) {return Result(a + b, a * b, a - b);
}// 可空返回
String? findName(int id) {if (id <= 0) {return null; // 返回null表示未找到}return "User$id";
}// 调用示例
int area = square(5); // 返回25
int volume = cube(3); // 返回27var result = calculate(3, 4);
var sum = result[0]; // 7
var product = result[1]; // 12var extResult = calculateExtended(3, 4);
var difference = extResult.difference; // -1String? name = findName(-1); // 返回null
// 使用空安全操作符
int? length = name?.length; // 如果name为null,则length为null
Python:
# 单值返回
def square(x):return x * x# 多值返回(通过元组)
def calculate(a, b):return a + b, a * b # 返回元组# 使用字典返回多个值
def calculate_extended(a, b):return {'sum': a + b,'product': a * b,'difference': a - b}# 可空返回
def find_name(id):if id <= 0:return None # 返回None表示未找到return f"User{id}"# 调用示例
area = square(5) # 返回25# 元组解包
sum_result, product = calculate(3, 4) # sum_result=7, product=12# 也可以直接获取元组
result = calculate(3, 4)
sum_result = result[0] # 7# 使用字典返回值
result = calculate_extended(3, 4)
difference = result['difference'] # -1name = find_name(-1) # 返回None
# 需要None检查
if name is not None:print(len(name))
ArkTS:
// 单值返回
function square(x: number): number {return x * x;
}// 多值返回(通过数组)
function calculate(a: number, b: number): number[] {return [a + b, a * b];
}// 使用对象返回多个值
interface Result {sum: number;product: number;difference: number;
}function calculateExtended(a: number, b: number): Result {return {sum: a + b,product: a * b,difference: a - b};
}// 可空返回
function findName(id: number): string | null {if (id <= 0) {return null; // 返回null表示未找到}return `User${id}`;
}// 调用示例
let area: number = square(5); // 返回25let result = calculate(3, 4);
let sum = result[0]; // 7
let product = result[1]; // 12let extResult = calculateExtended(3, 4);
let difference = extResult.difference; // -1let name = findName(-1); // 返回null
// 需要null检查
if (name !== null) {console.log(name.length);
}
Swift:
// 单值返回
func square(_ x: Int) -> Int {return x * x
}// 多值返回(通过元组)
func calculate(_ a: Int, _ b: Int) -> (sum: Int, product: Int) {return (a + b, a * b)
}// 使用结构体返回多个值
struct Result {let sum: Intlet product: Intlet difference: Int
}func calculateExtended(_ a: Int, _ b: Int) -> Result {return Result(sum: a + b, product: a * b, difference: a - b)
}// 可空返回
func findName(id: Int) -> String? {if id <= 0 {return nil // 返回nil表示未找到}return "User\(id)"
}// 调用示例
let area = square(5) // 返回25// 使用命名元组
let result = calculate(3, 4)
let sum = result.sum // 7
let product = result.product // 12// 也可以通过解构获取元组值
let (sum2, product2) = calculate(3, 4)let extResult = calculateExtended(3, 4)
let difference = extResult.difference // -1let name = findName(id: -1) // 返回nil
// 使用可选绑定
if let unwrappedName = name {print(unwrappedName.count)
}
// 或使用可选链
let length = name?.count // 如果name为nil,则length为nil
3.4 匿名函数与Lambda表达式
各语言匿名函数与Lambda表达式对比:
语言 | 匿名函数语法 | 闭包支持 | 函数引用 | 常见用途 |
---|---|---|---|---|
Java | (params) -> { body } | 支持(有限制) | 方法引用 Class::method | 事件处理、流操作 |
Kotlin | { params -> body } | 完全支持 | 函数引用 ::function | 高阶函数、集合操作 |
Dart | (params) { body } 或 (params) => expr | 支持 | 函数变量 | 事件处理、异步操作 |
Python | lambda params: expr 或函数对象 | 支持 | 函数变量 | 函数式编程、排序 |
ArkTS | (params) => { body } 或 (params) => expr | 支持 | 函数变量 | 事件处理、回调 |
Swift | { (params) -> ReturnType in body } | 完全支持 | 函数变量 | 高阶函数、集合操作 |
示例对比
Java:
// Lambda表达式
Runnable task = () -> {System.out.println("Task executed");
};// 带参数的Lambda
Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length();// 方法引用
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);// 在集合操作中使用Lambda
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> doubled = numbers.stream().map(n -> n * 2).collect(Collectors.toList());// 闭包示例
int factor = 2;
Function<Integer, Integer> multiplier = n -> n * factor;
// factor = 3; // 错误:Lambda中引用的变量必须是final或effectively final
Kotlin:
// Lambda表达式
val task = { println("Task executed") }// 带参数的Lambda
val sum = { a: Int, b: Int -> a + b }// 函数引用
val names = listOf("Alice", "Bob", "Charlie")
names.forEach(::println)// 在集合操作中使用Lambda
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }// 闭包示例
var factor = 2
val multiplier = { n: Int -> n * factor }
factor = 3 // 可以修改闭包中捕获的变量
println(multiplier(5)) // 输出15 (5 * 3)// 带接收者的Lambda
val html = buildString {append("<html>\n")append(" <body>\n")append(" <h1>Hello, world!</h1>\n")append(" </body>\n")append("</html>")
}
Dart:
// 匿名函数
var task = () {print("Task executed");
};// 箭头函数(单表达式)
var sum = (int a, int b) => a + b;// 函数作为参数
var names = ["Alice", "Bob", "Charlie"];
names.forEach((name) => print(name));// 在集合操作中使用Lambda
var numbers = [1, 2, 3, 4, 5];
var doubled = numbers.map((n) => n * 2).toList();// 闭包示例
var factor = 2;
var multiplier = (int n) => n * factor;
factor = 3; // 可以修改闭包中捕获的变量
print(multiplier(5)); // 输出15 (5 * 3)// 在异步编程中使用
Future<void> fetchData() async {await Future.delayed(Duration(seconds: 1));return "Data";
}fetchData().then((data) => print("Received: $data"));
Python:
# Lambda表达式
task = lambda: print("Task executed")# 带参数的Lambda
sum_func = lambda a, b: a + b# 函数作为参数
names = ["Alice", "Bob", "Charlie"]
list(map(print, names))# 在集合操作中使用Lambda
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda n: n * 2, numbers))# 列表推导式(替代Lambda的常用方式)
doubled_alt = [n * 2 for n in numbers]# 闭包示例
def create_multiplier(factor):def multiplier(n):return n * factorreturn multipliermult_by_3 = create_multiplier(3)
print(mult_by_3(5)) # 输出15 (5 * 3)# 在排序中使用Lambda
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda student: student[1], reverse=True)
ArkTS:
// 箭头函数
let task = () => {console.log("Task executed");
};// 单表达式箭头函数
let sum = (a: number, b: number) => a + b;// 函数作为参数
let names = ["Alice", "Bob", "Charlie"];
names.forEach((name) => console.log(name));// 在集合操作中使用Lambda
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map((n) => n * 2);// 闭包示例
let factor = 2;
let multiplier = (n: number) => n * factor;
factor = 3; // 可以修改闭包中捕获的变量
console.log(multiplier(5)); // 输出15 (5 * 3)// 在事件处理中使用
@Component
struct ButtonExample {build() {Column() {Button('Click Me').onClick(() => {console.log('Button clicked');})}}
}
Swift:
// 闭包表达式
let task = { print("Task executed") }// 带参数和返回值的闭包
let sum = { (a: Int, b: Int) -> Int inreturn a + b
}// 简化语法(类型推断)
let sum2 = { (a: Int, b: Int) in a + b }// 函数作为参数
let names = ["Alice", "Bob", "Charlie"]
names.forEach { print($0) }// 在集合操作中使用闭包
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }// 闭包捕获和修改外部变量
var factor = 2
let multiplier = { (n: Int) -> Int inreturn n * factor
}
factor = 3 // 可以修改闭包中捕获的变量
print(multiplier(5)) // 输出15 (5 * 3)// 尾随闭包语法
let sortedNames = names.sorted { $0.count < $1.count }// 在异步编程中使用
func fetchData(completion: @escaping (String) -> Void) {DispatchQueue.main.asyncAfter(deadline: .now() + 1) {completion("Data")}
}fetchData { data inprint("Received: \(data)")
}
3.5 构造函数:类的初始化与单例
各语言构造函数语法与单例模式实现对比:
语言 | 构造函数语法 | 多构造函数支持 | 单例模式实现 | 特殊特性 |
---|---|---|---|---|
Java | ClassName() { ... } | 重载 | 静态实例+私有构造函数 | 静态初始化块 |
Kotlin | constructor() { ... } | 主次构造函数、init块 | object关键字 | 伴生对象 |
Dart | ClassName() { ... } | 命名构造函数 | factory构造函数 | 初始化列表 |
Python | def __init__(self): ... | 单一构造方法+参数默认值 | 类方法或模块变量 | 魔术方法 |
ArkTS | constructor() { ... } | 重载 | 静态实例+私有构造函数 | 装饰器 |
Swift | init() { ... } | 指定/便利构造器 | 静态常量属性 | 可失败构造器 |
示例对比
Java:
// 基本构造函数
public class Person {private String name;private int age;// 无参构造函数public Person() {this.name = "Unknown";this.age = 0;}// 带参数的构造函数public Person(String name, int age) {this.name = name;this.age = age;}// 部分参数的构造函数(构造函数重载)public Person(String name) {this(name, 0); // 调用另一个构造函数}
}// 单例模式实现
public class Singleton {// 饿汉式单例(立即创建实例)private static final Singleton INSTANCE = new Singleton();private Singleton() {// 私有构造函数防止外部实例化}public static Singleton getInstance() {return INSTANCE;}
}// 懒汉式单例(延迟创建实例)
public class LazySingleton {private static LazySingleton instance;private LazySingleton() {// 私有构造函数}// 线程安全的懒加载public static synchronized LazySingleton getInstance() {if (instance == null) {instance = new LazySingleton();}return instance;}
}// 使用示例
Person p1 = new Person(); // 使用无参构造函数
Person p2 = new Person("Alice", 30); // 使用带参数的构造函数Singleton singleton = Singleton.getInstance(); // 获取单例实例
Kotlin:
// 基本构造函数
class Person(val name: String = "Unknown", // 主构造函数带默认值val age: Int = 0
) {// 初始化块init {println("Person created with name: $name and age: $age")}// 次构造函数constructor(name: String, age: Int, email: String) : this(name, age) {this.email = email}var email: String = ""
}// 单例模式实现(使用object关键字)
object Singleton {val name: String = "SingletonObject"fun doSomething() {println("Singleton is doing something")}
}// 伴生对象中的工厂方法
class User private constructor(val name: String) {companion object {// 工厂方法fun create(name: String): User? {return if (name.isNotEmpty()) User(name) else null}}
}// 使用示例
val p1 = Person() // 使用默认参数
val p2 = Person("Alice", 30) // 指定参数
val p3 = Person("Bob", 25, "bob@example.com") // 使用次构造函数// 使用单例
Singleton.doSomething() // 直接通过对象名访问// 使用工厂方法
val user = User.create("Alice") // 通过伴生对象的工厂方法创建实例
Dart:
// 基本构造函数
class Person {String name;int age;// 标准构造函数,使用初始化列表Person(this.name, this.age);// 命名构造函数Person.guest() {name = "Guest";age = 18;}// 带初始化列表的命名构造函数Person.withNameOnly(String name) : this.name = name, this.age = 0;// 重定向构造函数Person.child(String name) : this(name, 5);
}// 单例模式实现(使用factory构造函数)
class Singleton {// 私有静态实例static final Singleton _instance = Singleton._internal();// 私有构造函数Singleton._internal();// 工厂构造函数factory Singleton() {return _instance;}void doSomething() {print("Singleton is doing something");}
}// 使用示例
var p1 = Person("Alice", 30); // 标准构造函数
var p2 = Person.guest(); // 命名构造函数
var p3 = Person.withNameOnly("Bob"); // 带初始化列表的命名构造函数
var p4 = Person.child("Charlie"); // 重定向构造函数// 使用单例
var singleton1 = Singleton(); // 获取单例实例
var singleton2 = Singleton(); // 获取相同的实例
print(identical(singleton1, singleton2)); // 输出: true
Python:
# 基本构造函数
class Person:def __init__(self, name="Unknown", age=0):self.name = nameself.age = ageprint(f"Person created with name: {name} and age: {age}")# 单例模式实现(使用模块级变量)
class Singleton:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super(Singleton, cls).__new__(cls)return cls._instancedef __init__(self):# 初始化代码只会在第一次创建实例时执行if not hasattr(self, 'initialized'):self.initialized = Trueself.name = "SingletonObject"def do_something(self):print("Singleton is doing something")# 使用元类实现单例
class SingletonMeta(type):_instances = {}def __call__(cls, *args, **kwargs):if cls not in cls._instances:cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)return cls._instances[cls]class SingletonWithMeta(metaclass=SingletonMeta):def __init__(self, name="Default"):self.name = name# 使用示例
p1 = Person() # 使用默认参数
p2 = Person("Alice", 30) # 指定参数# 使用单例
singleton1 = Singleton()
singleton2 = Singleton()
print(singleton1 is singleton2) # 输出: True# 使用元类实现的单例
s1 = SingletonWithMeta("First")
s2 = SingletonWithMeta("Second") # name参数会被忽略,因为实例已存在
print(s1 is s2) # 输出: True
print(s1.name) # 输出: "First"(第二次初始化被忽略)
ArkTS:
// 基本构造函数
class Person {private name: string;private age: number;// 构造函数constructor(name: string = "Unknown", age: number = 0) {this.name = name;this.age = age;console.log(`Person created with name: ${name} and age: ${age}`);}// 重载构造函数(通过静态工厂方法模拟)static createWithEmail(name: string, email: string): Person {const person = new Person(name);person.email = email;return person;}email: string = "";
}// 单例模式实现
class Singleton {private static instance: Singleton;private name: string;// 私有构造函数private constructor() {this.name = "SingletonObject";}// 获取实例的静态方法static getInstance(): Singleton {if (!Singleton.instance) {Singleton.instance = new Singleton();}return Singleton.instance;}doSomething(): void {console.log("Singleton is doing something");}
}// 使用装饰器实现单例(ArkTS特有)
@Singleton
class SingletonWithDecorator {name: string = "DecoratedSingleton";doSomething(): void {console.log("Decorated singleton is doing something");}
}// 使用示例
let p1 = new Person(); // 使用默认参数
let p2 = new Person("Alice", 30); // 指定参数
let p3 = Person.createWithEmail("Bob", "bob@example.com"); // 使用静态工厂方法// 使用单例
let singleton = Singleton.getInstance();
singleton.doSomething();// 使用装饰器实现的单例
let decorated1 = new SingletonWithDecorator();
let decorated2 = new SingletonWithDecorator();
console.log(decorated1 === decorated2); // 输出: true
Swift:
// 基本构造函数
class Person {let name: Stringlet age: Intvar email: String?// 指定构造器init(name: String, age: Int) {self.name = nameself.age = ageprint("Person created with name: \(name) and age: \(age)")}// 便利构造器convenience init() {self.init(name: "Unknown", age: 0)}// 另一个便利构造器convenience init(name: String) {self.init(name: name, age: 0)}// 可失败构造器convenience init?(email: String) {guard email.contains("@") else {return nil // 无效的邮箱格式,返回nil}self.init()self.email = email}
}// 单例模式实现
class Singleton {// 静态常量属性作为单例实例static let shared = Singleton()// 私有构造函数private init() {print("Singleton initialized")}func doSomething() {print("Singleton is doing something")}
}// 使用示例
let p1 = Person() // 使用便利构造器
let p2 = Person(name: "Alice", age: 30) // 使用指定构造器
let p3 = Person(name: "Bob") // 使用另一个便利构造器// 可失败构造器示例
if let personWithEmail = Person(email: "alice@example.com") {print("Person created with email")
} else {print("Invalid email format")
}// 使用单例
let singleton = Singleton.shared
singleton.doSomething()
总结
通过对比六种移动端开发语言的函数与方法特性,我们可以看出:
-
函数定义与调用:Java要求函数必须在类内部定义;Kotlin、Dart、Python、ArkTS和Swift都支持顶层函数。Swift和Kotlin的类型系统最为严格,而Python最为灵活。
-
参数传递:除Python外,其他语言对基本类型都采用值传递,对象采用引用传递;Python则统一采用对象引用方式。各语言都支持可变参数和函数参数,但语法和实现机制有所不同。
-
返回值:所有语言都支持单值返回和多值返回(通过不同机制)。Kotlin、Swift和ArkTS的可空类型系统最为完善,提供了更安全的空值处理机制。
-
匿名函数与Lambda:所有语言都支持Lambda表达式或匿名函数,但在语法简洁性和功能上有差异。Kotlin和Swift的闭包支持最为完善,Java的Lambda表达式对变量捕获有限制。
-
构造函数:Java和Kotlin提供了多种构造函数机制,Swift的构造器设计最为严谨,Dart的命名构造函数最为灵活,Python的
__init__
方法简洁直观,ArkTS则结合了TypeScript和面向对象的特性。
总体而言,Kotlin和Swift在函数特性上最为现代化和全面,提供了丰富的语法糖和类型安全保障;Dart和ArkTS在移动开发领域提供了良好的平衡;Java保持了向后兼容性但引入了函数式特性;Python则以简洁灵活著称,适合快速开发。选择哪种语言,应根据项目需求、团队熟悉度和平台限制综合考虑。