Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in kotlin?

Tags:

kotlin

I need to define a variable and acces it like static variables in java. I want to acces this variable just by name of a class.


1 Answers

Put it inside of a companion object in your class

class Example {
    companion object { 
          val foo = 1
     }
}

Example.foo

If everything inside of your class is going to be static then you can make that class an object in Kotlin

object Example {

        val foo = 1
 }

Example.foo
like image 65
Rafa Avatar answered Feb 09 '26 07:02

Rafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!