[Kotlin] companion object == static method

In Kotlin, there is no static methods, but we can use companion object which works the same as static methods.

For example, a class:

package com.rsk

import java.security.Provider
import java.security.Security


class Providers {
    // similar as static
    companion object {
        fun getProviders(): List<Provider> {
            val providers = Security.getProviders();
            val listOfProviders: List<Provider> = providers.asList()
            return listOfProviders
        }
    }

    fun getProviders(): List<Provider> {
        val providers = Security.getProviders();
        val listOfProviders: List<Provider> = providers.asList()
        return listOfProviders
    }
}

You notice there are two functions called 'getProviders', the first one is inside companion object.

The companion is singelton.

Usage:

val providers = Security.getProviders();

For the second 'getProviders', usage:

val providers = Providers()
val allProviders = providers.getAllProviders()

As you can see, using companion object is musch cleaner way to write the code

原文地址:https://www.cnblogs.com/Answer1215/p/13822202.html