kotlin实现静态类和静态方法

1,364 阅读2分钟

kotlin静态类和静态方法的使用。

静态类:

object修饰的类是Singleton(单例),(java code style, 在Kotlin中有package-level方法替代静态方法).

/**
 * 
 * 静态类:类名前的class替换成object。
 *
 * 此类下的所有对象和函数,都是静态,所有方法都为静态方法,如工具类、常量池
 * 
 */
object ClassA {
    var isDebug = BuildConfig.DEBUG
    
    fun doSomething(): String {
        doSomeThing
    }
}

类中的方法调用:

ClassA.doSomething()

静态方法:


/**
 * 
 * 使用伴生对象的方式,实现静态方法或对象,即使用companion object {}包裹
 *
 */
class ClassA {
    companion object {
        var text
        
        fun func1() {
        }
    }
}

静态对象的调用:

ClassA.text

静态方法的调用:

ClassA.func1()

什么是伴生对象?

companion

意思大概就是在Kotlin中使用包级别的方法代替静态方法,因此companion object也是替代static变量用的。

package-level functions

Kotlin is designed so that there’s no such thing as a “static member” in a class. If you have a function in a class, it can only be called on instances of this class. If you need something that is not attached to an instance of any class, you define it in a package, outside any class (we call it package-level functions):

package foo

fun bar() {}

Class Objects

A class (not inner and not local) or trait may declare at most one class object associated with it. For example:

class Foo {
  class object {
    val bar = 1
  }

  val baz = 2
}

Here we have a class, Foo, that declares a class object, which in turn has a member property bar. This means that we can call bar directly on a class name (just like in Java):

println(Foo.bar)

Note that we can not call bar on an instance of Foo:

val foo = Foo()
println(foo.bar) // compilation error

That’s because bar is not a member of Foo, only of its class object. Class object is a separate entity associated with the class, and does not share members with its instances. Neither can we call baz on the class name:

prinltn(Foo.baz) // error

This is because baz is a member of Foo, not of its class object, so you can only call baz on instances of Foo.

Now, let’s look at how class objects work. First, there’s a separate JVM class generated for a class object, and bar is a member of that class. If you access class objects from Java, you have to say something like this:

/* Java */
Foo.object$.getBar()

Class object is an instance stored in a static field inside the class it is defined in, and its properties are accessed with getters/setters.

“Static constants” in Kotlin(blog.jetbrains.com/kotlin/2013…)