user12475206
user12475206

Reputation:

How to use a variable from another class in Kotlin?

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 ...

Upvotes: 9

Views: 20188

Answers (3)

Aung Phyo Zaw
Aung Phyo Zaw

Reputation: 1

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

Upvotes: 0

Ukesh Shrestha
Ukesh Shrestha

Reputation: 190

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}}

Upvotes: 2

GHH
GHH

Reputation: 2019

class A

class A {
    var isBlue = 1
}

class B

class B {

    var classA = A()

    fun demo(){

        classA.isBlue//get A member
    }
}

hope this helps.

Upvotes: 11

Related Questions