


Detailed explanation of how to implement static methods in Kotlin similar to Java or C#
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. ). 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?
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)} } } }
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
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; } }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
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 AppInfo{ var AppName = "Kotlin Message" var AppAuthor = "Riley Ge" fun toSimpleString() { println("AppName:$AppName,AppAuthor:$AppAuthor") } }
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!

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software