Can constant objects be used to assign values to constant or any type of data members? | Sololearn: Learn to code for FREE!
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?

12th Jun 2020, 7:01 AM
Prabhanshu Chaturvedi
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").
12th Jun 2020, 11:46 PM
Prabhanshu Chaturvedi
+ 4
Like this? object E { const val v = 2 } class T() { companion object { const val d = 5 const val n = E.v } }
13th Jun 2020, 12:51 AM
John Wells
John Wells - avatar
+ 4
Oh! Yes like that. Thank you.
13th Jun 2020, 1:15 AM
Prabhanshu Chaturvedi
+ 3
Constants must be known at compile time and can not be instance based.
13th Jun 2020, 12:55 AM
John Wells
John Wells - avatar
+ 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 } }
13th Jun 2020, 1:25 AM
John Wells
John Wells - avatar
+ 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?
12th Jun 2020, 7:54 PM
John Wells
John Wells - avatar