Delin Mathew
Delin Mathew

Reputation: 279

Accessing variables in Kotlin

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.

Upvotes: 1

Views: 2145

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81929

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

Upvotes: 1

Related Questions