Note: The following is just my personal opinion. If there are any mistakes, please point them out.
static method in kotlin
foreword
Static methods in kotlin are generally implemented through singleton classes, but singleton classes are not actually static in the true sense. If you want a real static method, you can use the @JvmStatic annotation or define a top-level method to achieve it.
Implemented using a singleton class
When all are static methods
object ClassName{
}
This completes the creation of a singleton class, writes all the methods into the class, and the method is a static method.
When only some methods are required to be static methods
class ClassName {
fun doSomething1() {
//dosmething
}
companion object{
fun doSomething2() {
//dosmething
}
fun doSomething3() {
//dosmething
}
}
}
where doSomething1()
is not a static method, doSomething2()
and doSomething3()
is a static method.
Implemented using annotations
class ClassName {
companion object {
@JvmStatic
fun doSomething() {
//dosomething
}
}
}
This will doSomething()
define a real static method.
Implemented using top-level methods
Define the top-level file, and the methods defined in this file are all top-level methods, which are also real static methods.
fun doSomething() {
//dosmething
}
at last
Static methods are generally used as tool classes, except that annotations are not commonly used, and others are very common in kotlin.