9

I just have a (hopefully) simple question. How do I make a variable in one class that can be accessed by another class in Kotlin?

Class A:

var isBlue = 1

Class B:

if isBlue==1 then ...
3
  • You need to reference an instance of the other class and use . dot notation to access its properties. someInstanceOfA.isBlue == 1. Commented Dec 3, 2019 at 16:42
  • I'm guessing you are very new to OOP? Please post the code you wrote so far! Commented Dec 3, 2019 at 16:42
  • I have no written code yet. I am just trying to make some sort of switch that determines which functions I'm gonna run in the other class. Commented Dec 3, 2019 at 16:52

3 Answers 3

11

class A

class A {
    var isBlue = 1
}

class B

class B {

    var classA = A()

    fun demo(){

        classA.isBlue//get A member
    }
}

hope this helps.

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

Comments

2

you can either create an instance of the object and access the property like this

ClassA().isBlue

or inherit the class and access the attribute like this.

ClassB:ClassA{ fun someFn(){if (isBlue == 1) do something}}

Comments

0

In java , just declare with " static " , no need to call class name , in Kotlin need to call class name , but null pointer exception , Such headache problem

Comments

Your Answer

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