Kotlin 参数关键字
最后修改于 2025 年 4 月 19 日
Kotlin 的函数参数提供了定义和调用函数的灵活方式。KDoc 中的 param
关键字用于记录函数参数。本教程通过实际例子探讨 Kotlin 中参数的用法。
基本定义
在 Kotlin 中,函数参数定义在函数名之后的括号内。param
关键字用于在 KDoc 注释中记录参数。Kotlin 支持命名参数、默认值和可变参数。
基本函数参数
Kotlin 中的函数参数定义时,先写名称,然后写类型。参数之间用逗号分隔。这是一个包含两个参数的简单函数示例。
package com.zetcode /** * Calculates the sum of two numbers * @param a the first number * @param b the second number * @return the sum of a and b */ fun sum(a: Int, b: Int): Int { return a + b } fun main() { val result = sum(5, 7) println(result) // Output: 12 }
这个例子展示了一个带有两个 Int 参数的基本函数。KDoc 注释使用 @param
来记录每个参数。该函数返回两个数字的和。
命名参数
Kotlin 允许使用命名参数调用函数。这使得代码更具可读性,并允许更改参数顺序。命名参数指定为 name = value
。
package com.zetcode /** * Creates a greeting message * @param name the person's name * @param greeting the greeting phrase * @return the complete greeting */ fun createGreeting(name: String, greeting: String): String { return "$greeting, $name!" } fun main() { val msg = createGreeting( name = "Alice", greeting = "Hello" ) println(msg) // Output: Hello, Alice! }
在这里,我们使用命名参数调用函数。使用名称时,顺序无关紧要。这对于具有许多参数的函数特别有用。
默认参数
Kotlin 支持默认参数值。如果省略参数,则使用其默认值。默认值在类型之后使用 = value
指定。
package com.zetcode /** * Formats a product description * @param name the product name * @param price the product price * @param currency the currency symbol (default "$") * @return formatted description */ fun formatProduct( name: String, price: Double, currency: String = "$" ): String { return "$name: $currency$price" } fun main() { val desc1 = formatProduct("Laptop", 999.99) val desc2 = formatProduct("Phone", 699.99, "€") println(desc1) // Output: Laptop: $999.99 println(desc2) // Output: Phone: €699.99 }
currency
参数的默认值为 "$"。我们可以省略它或提供不同的值。默认参数减少了对重载函数的需求。
可变参数
Kotlin 使用 vararg
关键字支持可变数量的参数(可变参数)。在函数内部,可变参数被视为指定类型的数组。
package com.zetcode /** * Calculates the average of numbers * @param numbers the numbers to average (vararg) * @return the average as Double */ fun average(vararg numbers: Int): Double { return numbers.average() } fun main() { val avg1 = average(1, 2, 3, 4, 5) val avg2 = average(10, 20, 30) println(avg1) // Output: 3.0 println(avg2) // Output: 20.0 }
numbers
参数被标记为 vararg
,允许任意数量的 Int 参数。该函数计算并返回平均值。可变参数必须是列表中的最后一个参数。
使用 @param 记录参数
KDoc 使用 @param
标签来记录函数参数。每个参数都应有一个描述,解释其目的和要求。
package com.zetcode /** * Validates user credentials * @param username the user's username (must be 4-20 chars) * @param password the user's password (must be 8+ chars) * @param allowSpecialChars if special chars are allowed in password * @return true if credentials are valid, false otherwise */ fun validateCredentials( username: String, password: String, allowSpecialChars: Boolean = true ): Boolean { // Validation logic here return username.length in 4..20 && password.length >= 8 && (allowSpecialChars || password.all { it.isLetterOrDigit() }) } fun main() { val isValid = validateCredentials( username = "user123", password = "securePass123" ) println(isValid) // Output: true }
此示例显示了使用 @param
进行的彻底参数文档记录。每个参数的约束都清楚地指定。良好的文档记录可以帮助其他开发人员正确使用您的函数。
参数中的解构
Kotlin 允许在参数中使用解构声明。这使您可以直接在参数列表中解包数据类。
package com.zetcode data class User(val name: String, val age: Int, val email: String) /** * Sends a welcome email to a user * @param user the user data to welcome * @param name the user's name (destructured) * @param email the user's email (destructured) */ fun sendWelcomeEmail(user: User, (name, _, email): User) { println("Sending welcome email to $name at $email") } fun main() { val user = User("Bob", 30, "bob@example.com") sendWelcomeEmail(user) // Output: Sending welcome email to Bob at bob@example.com }
在这里,我们在参数列表中解构 User 对象。下划线跳过 age 字段。解构使处理复杂参数的特定属性变得容易。
函数类型参数
Kotlin 函数可以接受其他函数作为参数。这些高阶函数对于创建灵活的 API 非常强大。
package com.zetcode /** * Applies a transformation to a string * @param input the string to transform * @param transform the transformation function * @return the transformed string */ fun transformString( input: String, transform: (String) -> String ): String { return transform(input) } fun main() { val result = transformString("hello") { it.uppercase() } println(result) // Output: HELLO val reversed = transformString("world") { it.reversed() } println(reversed) // Output: dlrow }
transform
参数是一个函数,它接受一个 String 并返回一个 String。我们传递不同的 lambda 表达式来以各种方式修改输入字符串。
参数的最佳实践
- 使用描述性名称: 选择清晰、有意义的参数名称,以表明目的。
- 彻底记录: 在 KDoc 中使用
@param
来解释每个参数的作用和约束。 - 限制参数计数: 具有许多参数的函数可能难以使用 - 考虑重构。
- 使用默认值: 默认参数减少了对重载函数的需求。
- 考虑命名参数: 命名参数使函数调用更具可读性,尤其是在有许多参数时。
来源
本教程深入介绍了 Kotlin 函数参数,包括基本用法、命名参数、默认值和可变参数。我们还探讨了使用 @param
进行参数文档记录,以及解构等高级功能。有效使用参数可以使您的 Kotlin 代码更灵活、更具可读性。
作者
列出 所有 Kotlin 教程。