首页 > 其他 > 详细

[Kotlin] companion object == static method

时间:2020-10-15 22:23:39      阅读:35      评论:0      收藏:0      [点我收藏+]

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

[Kotlin] companion object == static method

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!