移动端六大语言速记:第3部分 - 函数与方法

移动端六大语言速记:第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
    
    # 静态方法
    @staticmethod
    def 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");  // 修改会影响原始对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

键盘小码哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值