Home Backend Development C#.Net Tutorial Detailed explanation of how to implement static methods in Kotlin similar to Java or C#

Detailed explanation of how to implement static methods in Kotlin similar to Java or C#

Jun 04, 2017 am 09:41 AM

How to implement a static method in Kotlin similar to Java or C#, this article summarizes several methods, namely: package-level function, companionObjects

, extension functions and object declarations. This requires everyone to choose according to different situations.

You can find many such articles on the Internet. The official recommendation is package-level functions, and some people say to use companion objects (companion class

). These are good options, but they're not perfect, and we have better options in different situations. I have summarized several methods, namely: package-level functions, companion objects, extension functions and object declarations. This requires everyone to choose according to different situations.

1. Package-level functions

The difference between Kotlin and Java and C# is that you can declare functions

directly in the package. The method is the same as in the category, so I won’t go into details here. It is indeed a very good choice. It is suitable for methods where functions do not need to include internal classes for data sharing.

2. Companion object


Semantically speaking, companion functions are most similar to static methods in Java, so companion objects can completely implement static methods in Java All contents of the class. But using static methods in Java is sometimes no choice. In Kotlin, companion objects are just one of our options. Next I will introduce the companion objects. Have you ever noticed when using Java? When are the static variables
and methods in Java classes initialized? Is it when the static method is first called or when the corresponding Java class is loaded? The answer is when the Java class is loaded (that is, if you have called the instance variables and methods in the Java class, even if you have not used static variables and methods, the static variables have been initialized). Isn’t it appropriate to describe this phenomenon as accompanying?

In Kotlin, it is considered that there are two types of stuff in a class, one is the instance variables and methods in the Java class, and the other is the static variables and methods in the Java class. Kotlin packages static instances and methods into a companion class, and that's what it looks like. Here is an example:

fun main(args: Array<String>) {
 Books.getBestSellers()
}
class Books(var name: String, val page: Int) {
  fun getWordCount()=page*100
  companion object ComBooks{
    var bestSellers=arrayOf("Harry Potter\r\t","Lord of the Rings\r\t")
    fun getBestSellers() {
      bestSellers.forEach{v->println(v)}
    }
  }
}
Copy after login
The companion class is declared using companion. It is loaded in the class where the companion object is located, and the companion object is initialized, just like Java static members. It can be anonymous or have the same name as the containing class. There are two types of calls: Books.ComBooks.getBestSellsers()? or Books.getBestSellsers()?.

3. Extension functions

In Java, we often write Utils classes, which are often targeted at a certain The object performs operations on its functions that match its own program. Most of the methods are static methods, for example:

public class Utils {

  public static boolean isEmpty(String string){
    return string != null && string.length() == 0;
  }

  public static boolean isWeakEmpty(String string){
    return isEmpty(string) && string.trim().length() == 0;
  }
}
Copy after login

Of course we can use the above two methods to implement these static methods, but we have a better way.

fun String.isEmpty() = this != null && this.length == 0;

fun String.isWeakEmpty()= this.isEmpty() && this.trim().length == 0
Copy after login

The above two lines of code extend the String class with two functions. These two functions can be called like their native functions. The code is very beautiful. In fact, the extension function does not modify the internal content of the String class, and only adds two static functions to String. However, compared with Java's Utils class, the readability has been greatly improved.

4. Object declaration


Continue to consider the Utils class above. All methods (and sometimes variables) in this class are Static, this method does not need to be instantiated at all. In Java, we often declare this type as a static class. Is there a good solution for this situation in Kotlin? Is there a better solution than companion objects? Of course there is, object declaration is one.

Object declaration is very easy to understand. It uses the object keyword to declare an object. The object can use variables or methods, such as:

object AppInfo{
  var AppName = "Kotlin Message"
  var AppAuthor = "Riley Ge"
  fun toSimpleString() {
    println("AppName:$AppName,AppAuthor:$AppAuthor") 
  }
}
Copy after login

I found that Kotlin’s objects are really powerful. ! One thing everyone should pay attention to is that AppInfo is lazily initialized when it is accessed for the first time, which means that AppInfo is not initialized when the object is declared.

5. Summary


Having said so many methods, no one is worried that Kotlin does not have static methods now, right? Kotlin does not have it just because he Can do better. Moreover, Kotlin also gives you more choices. You can choose the appropriate method according to your actual situation to make your code efficient and beautiful.

###

The above is the detailed content of Detailed explanation of how to implement static methods in Kotlin similar to Java or C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

How to convert xml into word How to convert xml into word Apr 03, 2025 am 08:15 AM

There are three ways to convert XML to Word: use Microsoft Word, use an XML converter, or use a programming language.

What are the differences and connections between c and c#? What are the differences and connections between c and c#? Apr 03, 2025 pm 10:36 PM

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

C# multi-threaded method to prevent jamming C# multi-threaded method to prevent jamming Apr 03, 2025 pm 02:54 PM

The following ways to avoid "stuck" multithreading in C#: avoid time-consuming operations on UI threads. Use Task and async/await to perform time-consuming operations asynchronously. Update the UI on the UI thread via Application.Current.Dispatcher.Invoke. Use the CancellationToken to control task cancellation. Make rational use of thread pools to avoid excessive creation of threads. Pay attention to code readability and maintainability, making it easy to debug. Logs are recorded in each thread for easy debugging.

See all articles