New course! Every coder should learn Generative AI!
Try a free lesson+ 5
Can constant objects be used to assign values to constant or any type of data members?
That would be useful in keeping data protected from external changes to the object for they cannot be done. Is it possible?
6 Answers
+ 4
I don't have a code but I thought of writing one.
If there are constant variables in a class, so if we can assign a value to it as a user-defined input (which won't change throughout the program) to perform any operation where only one value is needed.
Example: To assign stats to a character in a game by getting an option to upgrade it, which when used cannot be changed (if the upgrade is used in "Health", it can't be used in "Attack").
+ 4
Like this?
object E {
const val v = 2
}
class T() {
companion object {
const val d = 5
const val n = E.v
}
}
+ 4
Oh! Yes like that. Thank you.
+ 3
Constants must be known at compile time and can not be instance based.
+ 3
You can even do math, as long as it can be calculated by the compiler, like:
class N() {
companion object {
const val t = T.d+T.n
}
}
+ 2
If the constant object or its properties have the correct data type for the assignment, they can be used. That is a read only operation so is perfectly fine usage of any constant.
Do you have an explict example you are asking about?