Dynamic variable names: Difference between revisions

Content added Content deleted
(Added FreeBASIC)
(Added Kotlin)
Line 365: Line 365:
var value = 42;
var value = 42;
this[varname] = value;</lang>
this[varname] = value;</lang>

=={{header|Kotlin}}==
Kotlin is a statically typed, compiled language and so it is not possible to create new variables, dynamically, at run time. However, you can make it look to the user like you are doing so with code such as the following which uses a map:
{{trans|FreeBASIC}}
<lang scala>// version 1.0.6

fun main(args: Array<String>) {
var n: Int
do {
print("How many integer variables do you want to create (max 5) : ")
n = readLine()!!.toInt()
}
while (n < 1 || n > 5)
val map = mutableMapOf<String, Int>()
var name: String
var value: Int
var i: Int = 1
println("OK, enter the variable names and their values, below")
do {
println("\n Variable $i")
print(" Name : ")
name = readLine()!!
if (map.containsKey(name)) {
println(" Sorry, you've already created a variable of that name, try again")
continue
}
print(" Value : ")
value = readLine()!!.toInt()
map.put(name, value)
i++
}
while (i <= n)
println("\nEnter q to quit")
var v: Int?
while (true) {
print("\nWhich variable do you want to inspect : ")
name = readLine()!!
if (name.toLowerCase() == "q") return
v = map[name]
if (v == null) println("Sorry there's no variable of that name, try again")
else println("It's value is $v")
}
}</lang>
Sample input/output:
{{out}}
<pre>
How many integer variables do you want to create (max 5) : 3
OK, enter the variable names and their values, below

Variable 1
Name : faith
Value : 1

Variable 2
Name : hope
Value : 2

Variable 3
Name : hope
Sorry, you've already created a variable of that name, try again

Variable 3
Name : charity
Value : 3

Enter q to quit

Which variable do you want to inspect : chastity
Sorry there's no variable of that name, try again

Which variable do you want to inspect : charity
It's value is 3

Which variable do you want to inspect : q
</pre>


=={{header|Lasso}}==
=={{header|Lasso}}==