1

How can I declare a variable globally in Kotlin such that a variable declared in Class A can be accessed in Class B?

val fpath: Path = Paths.get("")

I want to be able to access the variable fpath throughout the entire program/project. P.S. I am new to Kotlin. Any help would be appreciated.

1
  • Normally, you pass variables to the things that need it. Commented Feb 20, 2018 at 22:02

1 Answer 1

1

First: Accessing a property of another class isn’t hard as long as it’s visibility allows it. By default, without explicit visibility modifier, it is:

class A{
    val fpath= ...
}

class B(val a: A){
    fun xy() = print(“accessing property of A: ${a.prop}”)
}

Second: What you should rather do with your example variable fpath is defining it as a top-level element, i.e. directly in a file, which can be accessed from anywhere else by simply importing the element.

For example, you could have a Common.kt file in package com.x with fpath = Paths.get(...) in it. From another file you do import com.x.fpath and use it throughout the file.

Third: You could also define the variable in a companion object of A if it belongs there:

class A {
    companion object {
        val fpath = ...
    }
}

class B{
    fun xy() = print(“accessing property of A: ${A.fpath}”)
}
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.