1

I have 2 kotlin classes and both of them implement the interface myVariables. Inside myVariables is a variable named money. What I am trying to do is have the same variable(and keep its value too) be used inside both classes. Is this a good way to do it?

class MainActivity : myVariables, AppCompatActivity() {override val money = 0}
abstract class ShopActivity : myVariables, AppCompatActivity() {override val money = 0}

The interface:

interface myVariables {
val money: Int
}

What is a better way to use the same variable in both of my classes without redefining its value. For example if the variable has gained a value of 5 in the MainActivity class, I want to use the same variable with a value of 5 in the ShopActivity class.

I want the same effect as if this variable was global in the file that is using it, if that makes any sense.

2
  • If you need variable whose value could be access in any class and its value is the same which is in the other class then I think you can use static variable. Commented Apr 14, 2018 at 4:07
  • 1
    use companion object in kotlin to achieve this Commented Apr 14, 2018 at 4:13

1 Answer 1

8

You're looking for singleton. And the idiomatic way to create them in Kotlin is to create object (not class), which will hold your variables. Like this:

object MyVariables {
  const val string = "foo"
  val pops = 4
}

And then you can use it in your class like this:

class MyClass {
  fun myMethod() {
    println(MyVariables.string)
  }
}

Of course you can use vars, not vals if you need to change them. But be warned that having a global mutable state is generally a bad idea because it's hard to track over the code, where variable is changed from.


Also note that generally it's a bad idea to start names of interfaces from lowercase because it breaks conventions and makes code less readable. It took a couple seconds for me to understand that myVariables isn't variable name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.