zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    Java并发初识
    go交叉编译
    MRC与ARC混合开发配置
    Hibernate配置文件
    LEFT JOIN重复数据
    Ext.ViewPort布局
    Hibernate学习映射文件
    AjaxMethod方法
    DataBinder
    subsonic 获取记录数量
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13822202.html
Copyright © 2011-2022 走看看