简体   繁体   English

Kotlin 中的 Function 参数名称

[英]Function parameter names in Kotlin

I saw in some Kotlin samples the next syntax where the name of the parameter is set before the value being passed:我在一些 Kotlin 示例中看到了在传递值之前设置参数名称的下一个语法:

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

What is above the difference from the next syntax?与下一个语法有什么区别? Is it only visual or has some type of purpose?它只是视觉上的还是有某种目的?

LoginResult(LoggedInUserView(result.data.displayName))

According to the Kotlin Documentation :根据Kotlin 文档

When calling a function, you can name one or more of its arguments.调用 function 时,可以命名它的一个或多个 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. 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.当您在 function 调用中使用命名 arguments 时,您可以自由更改它们列出的顺序,如果您想使用它们的默认值,您可以完全不使用它们。

So essentially, they are helpful when you have a lot of parameters to a function.因此,本质上,当您对 function 有很多参数时,它们会很有帮助。 For example, instead of:例如,而不是:

doSomething(true, true, true)

We can name these parameters, for clarity:为了清楚起见,我们可以命名这些参数:

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

The compiled code is identical, this is for developer clarity only.编译后的代码是相同的,这只是为了让开发人员清楚。

The other use case is so you can mix up the order, if you'd like:另一个用例是,如果您愿意,您可以混合订单:

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

Again, the code that gets generated works the same way, this is also for developer clarity.同样,生成的代码以相同的方式工作,这也是为了让开发人员清楚。

yes, that only visualize your parameters value.是的,这只可视化您的参数值。 you can use it or not, and it will not make a trouble.你可以使用它或不使用它,它不会造成麻烦。

and it's special它很特别

see my example of my data class查看我的数据示例 class

data class Movie(
    var title: String? = null,
    var poster: Int? = 0,
    var originalLang: String? = null
)

then you can easily put the constructor without see the stream那么您可以轻松放置构造函数而无需看到 stream

like:喜欢:

val movie = Movie(poster = 9, originalLang = "en", title = "Overlord")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM