Reputation: 589
I saw in some Kotlin samples the next syntax where the name of the parameter is set before the value being passed:
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))
Upvotes: 2
Views: 1874
Reputation: 34
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
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
like :
val movie = Movie(poster = 9, originalLang = "en", title = "Overlord")
Upvotes: 1
Reputation: 31690
According to 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.
So essentially, they are helpful when you have a lot of parameters to a 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.
Upvotes: 4