HelloCW
HelloCW

Reputation: 2255

Why can I invoke a fun without passing parameter name in Kotlin?

There are 4 parameters with default value in function joinToString, in my mind, I should pass parameter value by order when I omit parameter name.

So I think the Code println(letters.joinToString( transform={ it.toLowerCase() } ) ) is right.

But in fact the Code println(letters.joinToString { it.toLowerCase() } ) is right too, why?

fun <T> Collection<T>.joinToString(
        separator: String = ", ",
        prefix: String = "",
        postfix: String = "",
        transform: (T) -> String = { it.toString() }
): String {
    val result = StringBuilder(prefix)

    for ((index, element) in this.withIndex()) {
        if (index > 0) result.append(separator)
        result.append(transform(element))
    }

    result.append(postfix)
    return result.toString()
}


fun main(args: Array<String>) {  
    val letters = listOf("Alpha", "Beta")

    println(letters.joinToString { it.toLowerCase() } )               //It's Ok    
    println(letters.joinToString( transform={ it.toLowerCase() } ) )  //It's OK

}

Upvotes: 1

Views: 414

Answers (2)

user2340612
user2340612

Reputation: 10704

In addition to @Dan's answer, you don't need to provide a named argument, but if you do so then you're forced to use the named argument for all the following arguments (from the documentation: "all the positional arguments should be placed before the first named one"). In your case the only named argument you're providing is the last one, and all other arguments have default values so you're not forced to provide them, as long as the default value is fine for you.

Upvotes: 0

Dan Hartman
Dan Hartman

Reputation: 194

Because you're using a different syntax.

If the last param of a method is a method reference then you can omit the parenthesis and just pass in the function with the { brackets.

it in this case becomes T that you were passing into the function

println(letters.joinToString { it.toLowerCase() } )

Below is what you thought you were entering. This wouldn't compile and would require the named argument or for the params to be in the right order. You would also have to change the syntax from using it to using the regular functional syntax

println(letters.joinToString(it.toLowerCase()))

Upvotes: 6

Related Questions