Kotlin 中的函数参数名称

标签 function kotlin parameters

我在一些 Kotlin 示例中看到了下一个语法,其中参数名称在传递值之前设置:

LoginResult(success = LoggedInUserView(displayName = result.data.displayName))

上面的语法与下面的语法有什么区别?它只是视觉效果还是有某种目的?

LoginResult(LoggedInUserView(result.data.displayName))

最佳答案

根据the Kotlin Documentation :

When calling a function, you can name one or more of its arguments. This may be helpful when a function has a large number of arguments, and it's difficult to associate a value with an argument, especially if it's a boolean or null value.

When you use named arguments in a function call, you can freely change the order they are listed in, and if you want to use their default values you can just leave them out altogether.

本质上,当函数有很多参数时它们会很有帮助。例如,代替:

doSomething(true, true, true)

为了清楚起见,我们可以命名这些参数:

doSomething(
   first = true,
   second = true,
   third = true
)

编译后的代码是相同的,这只是为了让开发人员清楚起见。

另一个用例是,如果您愿意,您可以混合顺序:

doSomething(
    third = true,
    first = false,
    second = false
)

同样,生成的代码以相同的方式工作,这也是为了开发人员清楚。

关于Kotlin 中的函数参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67220911/

相关文章:

java - 无法加载admob广告错误:3 ERROR_CODE_NO_FILL

java - Android 应用程序在多次切换 fragment 时崩溃

javascript - 在链接中使用 # 而不是 GET params = 更快?

r - 将 uniroot 函数与 dplyr 管道一起使用

function - 是否有任何宏不能表示为函数?

Android - 触发 MainActivity 以从自定义 View 执行某些操作

c++ - 函数调用中的数据类型不匹配

c# - 一种通用的集中式参数记录器方法,在 C# 中

postgresql - 与没有函数包装器的查询相比,SQL 函数非常慢

c - strcpy() 返回值