Kotlin 默认参数和命名参数

Kotlin 默认参数

在 Kotlin 中,您可以在函数定义中为参数提供默认值。

如果调用函数时传入了参数,则使用这些参数作为实参。但是,如果调用函数时未传入参数,则使用默认参数。


默认参数如何工作?

情况 I:传入所有参数


Both arguments passed to the function

函数 foo() 接受两个参数。这些参数提供了默认值。但是在上面的程序中,foo() 函数通过传入两个参数来调用。因此,不使用默认参数。

foo() 函数内部,letternumber 的值将分别为 'x'2

情况 II:未传入所有参数


All arguments are not passed to the function

在这里,只向 foo() 函数传入了一个(第一个)参数。因此,第一个参数使用了传入函数的值。但是,由于在函数调用时未传入第二个参数,第二个参数 number 将采用默认值。

foo() 函数内部,letternumber 的值将分别为 'y'15

情况 III:未传入任何参数


No arguments passed to the function

在这里,foo() 函数在未传入任何参数的情况下被调用。因此,两个参数都使用其默认值。

foo() 函数内部,letternumber 的值将分别为 'a'15


示例:Kotlin 默认参数

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    println("Output when no argument is passed:")
    displayBorder()

    println("\n\n'*' is used as a first argument.")
    println("Output when first argument is passed:")
    displayBorder('*')

    println("\n\n'*' is used as a first argument.")
    println("5 is used as a second argument.")
    println("Output when both arguments are passed:")
    displayBorder('*', 5)

}

运行程序后,输出将是

Output when no argument is passed:
===============

'*' is used as a first argument.
Output when first argument is passed:
***************

'*' is used as a first argument.
5 is used as a second argument.
Output when both arguments are passed:
*****

Kotlin 命名参数

在讨论命名参数之前,让我们稍微修改一下上面的代码。

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    displayBorder(5)
}

在这里,我们试图将第二个参数传递给 displayBorder() 函数,并为第一个参数使用默认参数。但是,此代码将导致错误。这是因为编译器认为我们正在尝试将 5(Int 值)赋给 character(Char 类型)。

为了解决这种情况,可以使用命名参数。方法如下:


示例:Kotlin 命名参数

fun displayBorder(character: Char = '=', length: Int = 15) {
    for (i in 1..length) {
        print(character)
    }
}

fun main(args: Array<String>) {
    displayBorder(length = 5)
}

运行程序后,输出将是

=====

在上面的程序中,我们使用了命名参数(length = 5),指定函数定义中的 length 参数将采用此值(参数的位置无关紧要)。

Named Arguments in Kotlin

在程序中,第一个参数 character 使用默认值 '='

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战