https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

01/21/2021, 7:04 PM
Noob here when it comes to companion objects. I basically have a
Copy code
class Blah {
companion object {
//HERE
}
fun somemethod2(){
//THERE
}
}
How can I define a variable that can be used in "HERE" and "THERE"? I know I can define
val MY_CONST
to the top of the file (outside of class declaration) but doesn't that make it global to all my classes? I just want it in the scope of the companion and the class.
l

Luke

01/21/2021, 7:07 PM
You can declare something private in the companion. It will only be available in the companion and the class.
3
c

Colton Idle

01/21/2021, 7:18 PM
Really? Snap. Thanks!
v

Vampire

01/21/2021, 10:01 PM
Actually for the most part it is better to not use a companion object imho. If you needed something static, declare it top level, if you need it only in that file, declare it private. Only if the requirement is, that you want to access the "thing" using the enclosing class name use a companion object.
2 Views