Kotlin 中的函数参数名称
Function parameter names in Kotlin
我在一些 Kotlin 示例中看到下一个语法,其中参数名称在传递值之前设置:
LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
上面和下一个语法有什么区别?它只是视觉效果还是有某种目的?
LoginResult(LoggedInUserView(result.data.displayName))
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
)
同样,生成的代码以相同的方式工作,这也是为了开发人员的清晰度。
是的,这只会可视化您的参数值。
你可以用也可以不用,不会惹事的。
而且很特别
查看我的数据示例class
data class Movie(
var title: String? = null,
var poster: Int? = 0,
var originalLang: String? = null
)
然后你可以很容易地把构造函数看不到流
喜欢:
val movie = Movie(poster = 9, originalLang = "en", title = "Overlord")
我在一些 Kotlin 示例中看到下一个语法,其中参数名称在传递值之前设置:
LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
上面和下一个语法有什么区别?它只是视觉效果还是有某种目的?
LoginResult(LoggedInUserView(result.data.displayName))
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
)
同样,生成的代码以相同的方式工作,这也是为了开发人员的清晰度。
是的,这只会可视化您的参数值。 你可以用也可以不用,不会惹事的。
而且很特别
查看我的数据示例class
data class Movie(
var title: String? = null,
var poster: Int? = 0,
var originalLang: String? = null
)
然后你可以很容易地把构造函数看不到流
喜欢:
val movie = Movie(poster = 9, originalLang = "en", title = "Overlord")