[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

posted @ 2020-10-15 18:30  Zhentiw  阅读(145)  评论(0)    收藏  举报