How to pass a value to an object class?
# announcements
m
How to pass a value to an object class?
r
The whole point of an object is that it is a singleton - there can be no other instance than the declared one. So you cannot construct another one with a different value.
m
I don't need another instance. I just need the object class to have a value that it should get from outside while being created. Is there such a possibility?
c
Sure, just give it a mutable property. https://pl.kotl.in/YLVzbi87e
Copy code
object MySingleton {
    var aProperty: String = ""
}

fun main() {
    MySingleton.aProperty = "another value"
    println(MySingleton.aProperty) // prints "another value" 
}
Note that this won’t work on Kotlin/Native because of its mutability restrictions
r
Did you mean like this?
Copy code
object Foo {
    val x = System.getProperty("goo")
    val y = System.getenv()["MY_ENV_VAR"]
}
n
you might actually be looking for the singleton concept, which Guice/Spring/IoC will provide
(obviously you don't need those for singletons, just an example)