简体   繁体   中英

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:

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 :

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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