Add a variable to a class instance at runtime: Difference between revisions
Content added Content deleted
(→{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details) |
|||
Line 594: | Line 594: | ||
However, as in the case of Groovy, we can ''make it appear'' as though variables are being added at runtime by using a Map or similar structure. For example: |
However, as in the case of Groovy, we can ''make it appear'' as though variables are being added at runtime by using a Map or similar structure. For example: |
||
<lang scala>// version 1.1. |
<lang scala>// version 1.1.2 |
||
class SomeClass { |
class SomeClass { |
||
Line 604: | Line 604: | ||
println("Create two variables at runtime: ") |
println("Create two variables at runtime: ") |
||
for (i in 1..2) { |
for (i in 1..2) { |
||
println(" Variable #$i:") |
println(" Variable #$i:") |
||
print(" Enter name : ") |
print(" Enter name : ") |
||
val name = readLine()!! |
val name = readLine()!! |
||
Line 616: | Line 616: | ||
val name = readLine()!! |
val name = readLine()!! |
||
val value = sc.runtimeVariables[name] |
val value = sc.runtimeVariables[name] |
||
if (value == null) |
if (value == null) |
||
println("There is no variable of that name, try again") |
println("There is no variable of that name, try again") |
||
else { |
else { |
||
println("Its value is '${sc.runtimeVariables[name]}'") |
println("Its value is '${sc.runtimeVariables[name]}'") |