Kotlin series: top-level functions and attributes, top-level functions of kotlin Series

Source: Internet
Author: User

Kotlin series: top-level functions and attributes, top-level functions of kotlin Series

Let's take a look at top-level functions and attributes in Kotlin today.

Problems encountered

As we all know, in Java, all codes exist based on classes. Our so-called Functions Act as class methods, and our so-called attributes act as class attributes. However, in some cases, we find that some methods may not belong to a specific class, and some attributes do not belong to a specific class. Therefore, we have created many Java tool classes and attribute constant classes, just like below.

Java code

public class Constant {    public static final String BASE_URL = "https://www.xxx.top:8080";}
public class StrUtil {    public static String joinToStr(Collection
 
   collection){        //...        return "";    }}
 

In fact, the above class is only used to carry our static attributes and methods, and serves as a container for static methods and attributes. This is the problem we are currently encountering. There are a lot of useless container classes, let's take a look at how Kotlin handles this problem.

Top-level functions

In Java, the class is at the top layer, and the class contains attributes and methods. In Kotlin, the function is at the class position. We can directly place the function on the top layer of the code file, so that it does not belong to any class. As shown belowWrite the following Kotlin code in the Str. kt file.

Kotlin code

package utilfun joinToStr(collection: Collection
  
   ): String{    //....    return "";}
  

Please note that we put it in the util package, which is very important when we call this class.
Let's take a look at how to call it in another Kotlin class.

Kotlin code

import util.joinToStrfun main(args: Array
  
   ){    joinToStr(collection = listOf("123", "456"))}
  

Have you seen it? We can useImport package name. function name to import the function we will use, and then you can use it directly, is it super convenient. Let's take a look at how to call the above method in Java.

Java code

import java.util.ArrayList;import util.StrKt;public class Main { public static void main(String[] args) { StrKt.joinToStr(new ArrayList<>()); }}

Because classes must exist in Java, the compiler places the code in the Str. kt file inStrKt class, and then put the defined Kotlin function as a static method, so in Java, import this class through mport first, and thenClass Name. method name to call.

Sometimes you think that the class name automatically generated by Kotlin is not good, you can@ File: The JvmName annotation is used to customize the class name, as shown below.

@file:JvmName("StrUtil")package utilfun joinToStr(collection: Collection  ): String{ //.... return "";} 

Note that,This annotation must be placed at the beginning of the file, before the package name.
When importing and calling classes in Java, we need to use our custom class names for operations, just like this.

import java.util.ArrayList;import util.StrUtil;public class Main { public static void main(String[] args) { StrUtil.joinToStr(new ArrayList<>()); }}
Top-level attributes

After learning about top-level functions, let's look at the top-level attributes. The top-level attribute directly places the attribute on the top of the file and is not attached to the class. The attributes defined at the top layer includeVar variables andVal constant, as shown below.

Kotlin code

package configvar count = 0val REQUEST_URL = "https://localhost:8080/"const val BASE_URL = "https://www.xxx.top/"

Here, I have defined three top-level attributes. You may not be able to understand them in some places, but you are not in a hurry. Let's first look at how to use them in Kotlin and Java, and then we will understand them again.

Use in Kotlin

Import config. countfun main (args: Array  ) {// Use the var variable count ++ // use the val constant config. REQUEST_URL // use the const val constant config. BASE_URL} 

You will find that in Kotlin, you can use it directly as long as it is imported, which is the same as the use of top-level attributes.

Use in Java

Import config. apiConfigKt; public class Main {public static void main (String [] args) {// use the var variable ApiConfigKt. setCount (12); System. out. println (ApiConfigKt. getCount (); // use the val constant System. out. println (ApiConfigKt. getREQUEST_URL (); // use the const val constant System. out. println (ApiConfigKt. BASE_URL );}}

First, the import is affirmative. Calling this method through the class name class is also consistent with the rules in the top-level function. Then you will find that Kotlin generates the get and set methods for the var variable, and then generates the get method for the val constant. Finally, our const val constant is equivalent to the public static final constant of Java, you can directlyClass Name. Constant name to call.

Conclusion

Kotlin uses top-level functions and top-level attributes to help us eliminate common static tool classes in Java, so that our code is more neat and worth a try.

Related Article

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.