Add a variable to a class instance at runtime: Difference between revisions
Content added Content deleted
(Added Kotlin) |
|||
Line 587: | Line 587: | ||
e.foo = 1 |
e.foo = 1 |
||
e["bar"] = 2 // name specified at runtime</lang> |
e["bar"] = 2 // name specified at runtime</lang> |
||
=={{header|Kotlin}}== |
|||
Adding variables to an object at runtime is not possible in Kotlin (at least in the version targeting the JVM) which is a statically typed language and therefore the names of all class variables need to be known at compile time. |
|||
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.1 |
|||
class SomeClass { |
|||
val runtimeVariables = mutableMapOf<String, Any>() |
|||
} |
|||
fun main(args: Array<String>) { |
|||
val sc = SomeClass() |
|||
println("Create two variables at runtime: ") |
|||
for (i in 1..2) { |
|||
println(" Variable #$i:") |
|||
print(" Enter name : ") |
|||
val name = readLine()!! |
|||
print(" Enter value : ") |
|||
val value = readLine()!! |
|||
sc.runtimeVariables.put(name, value) |
|||
println() |
|||
} |
|||
while (true) { |
|||
print("Which variable do you want to inspect ? ") |
|||
val name = readLine()!! |
|||
val value = sc.runtimeVariables[name] |
|||
if (value == null) |
|||
println("There is no variable of that name, try again") |
|||
else { |
|||
println("Its value is '${sc.runtimeVariables[name]}'") |
|||
return |
|||
} |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
Sample input/output: |
|||
<pre> |
|||
Create two variables at runtime: |
|||
Variable #1: |
|||
Enter name : a |
|||
Enter value : rosetta |
|||
Variable #2: |
|||
Enter name : b |
|||
Enter value : 64 |
|||
Which variable do you want to inspect ? a |
|||
Its value is 'rosetta' |
|||
</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |