Search code examples
kotlininstance

How can I get a variable without creating a new instance Kotlin


I'm learning Kotlin and I face some problems.

I want to get a variable from another class but when I call it, there is a new instance of the class who have the variable.

In Java, we're doing this

class Main {
    public static void main(String[] args) {
        SomeText.text = "another text";
        System.out.println(SomeText.text);
    }
}

class SomeText {
    public static String text = "My Text";
}

And the result is "another text".

But in Kotlin if I'm using this :

fun main(args: Array<String>) {
    SomeText().text = "Another text"
    println(SomeText().text)
}

class SomeText{
    var text = "My Text"
}

The result is "My Text".

Do you know how can I get the variable and edit it without creating a new instance ? I tried the SomeText::text but it return a KMutableProperty1 instead of a String.


Solution

  • You can simulate static in Kotlin by using companion objects. So the following in Java

    class SomeText {
        public static String text = "My Text";
    }
    

    will be in Kotlin

    class SomeText {
        companion object {
            var text = "My Text"
        }
    }
    

    Then, you just need to update your main:

    fun main(args: Array<String>) {
        SomeText.text = "Another text"
        println(SomeText.text)
    }