码迷,mamicode.com
首页 > 其他好文 > 详细

[Kotlin] companion object == static method

时间:2020-10-16 10:59:03      阅读:22      评论:0      收藏:0      [点我收藏+]

标签:you   return   sid   port   str   ice   java   amp   com   

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

标签:you   return   sid   port   str   ice   java   amp   com   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!