Kotlin series: named parameters and default parameters, and kotlin series named Parameters

Source: Internet
Author: User

Kotlin series: named parameters and default parameters, and kotlin series named Parameters

Let's take a look at the name parameters and default parameters of Kotlin today.

If you have learned Python, you must be familiar with these two concepts. Today we will learn a wave of default parameters and named parameters in Kotlin.

Problems encountered

To illustrate the necessity of naming parameters and default parameters, we will first throw a question about how to print a set and customize its printing form. In Java, the most common idea is to rewrite the toString () method or write a tool class for printing a set, such as the following Java code.

Java code

public class Main {    public static void main(String[] args) {        List
 
   mArrayList = new ArrayList
  
   (){            @Override            public String toString() {                StringBuilder stringBuilder = new StringBuilder();                for (int i = 0; i < this.size(); i++) {                    stringBuilder.append(this.get(i));                    if (i < this.size() - 1){                           stringBuilder.append(";");                    }                }                return stringBuilder.toString();            }        };        mArrayList.add("123");        mArrayList.add("456");        mArrayList.add("789");        System.out.println(mArrayList);    }}
  
 

We have rewritten the toString () method above. Let's see how it works in Kotlin? Let's first look at the default Print Style in Kotlin.

Kotlin code

Fun main (args: Array
 
  
) {Val list = listOf
  
   
("123", "456", "789") println (list)} // print the result: [123,456,789]
  
 

Now we will first use Kotlin to write a function that customizes and prints the set style.

Kotlin code

fun 
 
   joinToString(collection: Collection
  
   , separator: String,                     prefix: String, suffix: String): String{    val result = StringBuilder(prefix)    for ((index, element) in collection.withIndex()){        if (index > 0){            result.append(separator)        }        result.append(element)    }    result.append(suffix)    return result.toString();}
  
 

The above method defines a tool class by yourself and customizes the Print Style by inputting different parameters.

Naming Parameters

Let's take a look at how to call the above functions and talk about the problems.

Kotlin code

println(joinToString(list, ";", "(", ")"))

Obviously there is a very inconvenient place here. If we don't use the IDE prompts and view the method definition, we can hardly understand the specific meaning of each parameter we pass to the function, so this timeThe name parameter appears. You can see the name. It is the name of the parameter, which makes it clearer for us to input and view the parameter, as shown below.

Kotlin code

println(joinToString(list, ";", "(", ")"))println(joinToString(collection = list, separator = ";", prefix = "(", suffix = ")"))println(joinToString( separator = ";", collection = list, prefix = "(", suffix = ")"))

As you can see, we have added a name before each input parameter. Is this intuitive? Because the parameter here is specified by name, therefore, the order of parameters can be different from that of the defined function. The preceding three methods can be called correctly.
But here are some notes:
1. If we have already specified a parameter name, the parameter after this parameter must also be specified, so that it will not cause confusion, and the Kotlin compiler will not understand your intention.
2. The name parameter format can only be used for Kotlin functions. It cannot be used for Java functions, as shown below.

// Java code public class Main {public static void javaFun (String name) {System. out. println (name) ;}// Kotlin code fun main (args: Array
  
   
) {// An error is reported. [The name parameter cannot be used for Java functions] println (Main. javaFun (name = "bingjianit "))}
  
Default parameters

Let's go back to the requirement at the beginning of the article. If we want to use the function written in Kotlin, we can use ",", when we pass in the separator, we use the introduced separator, that is, to make some parameters of our function have the default value. In fact, we can implement the same requirement through the overload function in Java, but there will be many overload functions. In Kotlin, we can implement this requirement through the default parameters.

Kotlin code

fun 
  
    joinToString2(collection: Collection
   
    , separator: String = ",",                     prefix: String = "[", suffix: String = "]"): String{    val result = StringBuilder(prefix)    for ((index, element) in collection.withIndex()){        if (index > 0){            result.append(separator)        }        result.append(element)    }    result.append(suffix)    return result.toString();}
   
  

In the above Code, we have specified the default values for the following three parameters. When we do not input a value, we use the default value. When we input a value, we use our own parameter. We can call it like below.

Kotlin code

// Output [123,456,789] println (jow.string2 (list) // output [123; 456; 789] println (jow.string2 (list, separator = ";"))

We can see that the default parameters and named parameters are used in combination here.

Since Kotlin can interoperate with Java, how can the above functions be called in Java? Because Java does not support default parameters, every parameter must be input for the function. As shown below:
InThe Str. kt file contains the default function defined above.

// Call [All parameters must be input] System. out. println (StrKt. jow.string2 (mArrayList, "{", "}") in Java ,",","{","}"));

Of course, if you do not want to write such a complex statement, you can add a @ JvmOverloads annotation to the default function generation in Kotlin. the compiler will automatically generate an overload function for each default parameter, as shown below:

Kotlin code

@JvmOverloadsfun  joinToString2(collection: Collection  , separator: String = ",", prefix: String = "[", suffix: String = "]"): String{ val result = StringBuilder(prefix) for ((index, element) in collection.withIndex()){ if (index > 0){ result.append(separator) } result.append(element) } result.append(suffix) return result.toString();}  

The generated Java overload functions are as follows:
Java code

public static  T joinToString2(Collection  collection);public static  T joinToString2(Collection  collection, String separator);public static  T joinToString2(Collection  collection, String separator, String prefix);public static  T joinToString2(Collection  collection, String separator, String prefix, String suffix);        

In this way, we do not need to pass so many parameters during the call.

Conclusion

Kotlin combines the excellent features of multiple languages, becomes a concise and exquisite programming language, and also has seamless interoperability with Java.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.