Kotlin static methods and variables

后端 未结 4 1276
南方客
南方客 2020-11-30 05:15

I want to be able to save a class instance to a public static variable but I can\'t figure out how to do this in Kotlin.

class Foo {

    public static Foo i         


        
4条回答
  •  鱼传尺愫
    2020-11-30 06:08

    first you create a simple class then after create a block followed by companion object keyword

    for example:

    class Test{
    
        companion object{
    
            fun  getValue(): String{
    
               return "Test String"
    
            }
        }
    }
    

    you can call this class function using class name dot function name

    for example:

    // here you will get the function value
    Test.getValue() 
    

提交回复
热议问题