+ 2

Naming objects based on values of variables in Kotlin

Short version: How do you reference the value of a variable in Kotlin, like in a string where you use $ to tell the compiler that the following part is a variable. Can you just type $variable to reference the value of variable anywhere in your code? Long version: I am trying to make a game where the player chooses a type of character by its name, and the game loads the character as an object with all of the default properties. However, to do this, every new object will have to have a different name and I am not sure how to go around doing this. I think this code should work val characterName = "$characterType" + characterCount val "$characterName" = Characters() "$characterName".name("$characterName") where characterCount is an incremented variable that counts the number of characters already created. In the first line, the character will be named by its type plus what number it is i.e. Archer5. In the second line, an object with the name being the value of characterName is created in the Characters class. Finally, in the last line, a function is ran on the object giving its input as the name. I know how to make a program like this in other languages, but I do not use Java and am trying to learn Kotlin, and have not used it much, so if you could ignore any stupid mistakes that come with being a Kotlin noob, that would be great! (By the way, I do not need code, I just would like to know how to reference the value of a variable in Kotlin, as I believe that "$characterName" can't be used anywhere. Also, I haven't completed the basic structure of the program like where input comes from, so I can not test this yet. Sorry about that!)

15th Jun 2019, 6:55 PM
Rasmit Devkota
Rasmit Devkota - avatar
1 Respuesta
+ 4
My suggestion would be a MutableList variable for each character type. When a new instance is created, add it to the list. val characters = mutableListOf<Characters>() val newest = Characters() characters.add(newest) If your characterCount is zero based, you can access as: val current = characters[characterCount]
19th Jun 2019, 4:35 PM
John Wells
John Wells - avatar