Define multiple variables at once in Kotlin (e.g Java : String x,y,z;)
VariablesKotlinVariables Problem Overview
I was wondering if there is any way to define multiple variables in Kotlin at once like in Java and almost every other existing language in the world .
like in Java :
String x = "Hello World!", y = null, z;
Variables Solutions
Solution 1 - Variables
You can declare (and assign) multiple variables in one line by using semicolons (;
):
val number = 42; val message = "Hello world!";
You can also declare (and assign) multiple properties in the same line similarly:
class Example {
var number = 42; var message = "Hello world!";
}
A runnable example illustrating both insights that you can [try online at tio.run][TIO-k9uvkon6] (it also worked fine in my local environment using Kotlin version 1.1.2-5 (JRE 1.8.0_144-b01)):
class Example {
// declaring multiple properties in a single line
var number:Int; var message:String;
// constructor that modifies the parameters to emphasize the differences
constructor(_number:Int, _message:String) {
number = _number * 2
message = _message.toUpperCase()
}
}
fun main(args: Array<String>) {
// declaring multiple read-only variables in a single line
val number = 42; val message = "Hello world!";
// printing those local variables
println("[main].number = " + number)
println("[main].message = " + message)
// instantiating an object and printing its properties' values
val obj = Example(number,message)
println("[Example].number = " + obj.number)
println("[Example].message = " + obj.message)
}
fun main(args: Array<String>) {
// declaring multiple read-only variables in a single line
val number = 42; val message = "Hello world!";
// printing those local variables
println("[main].number = " + number)
println("[main].message = " + message)
// instantiating an object and printing its properties' values
val obj = Example(number,message)
println("[Example].number = " + obj.number)
println("[Example].message = " + obj.message)
}
Execution output:
[main].number = 42
[main].message = Hello world!
[Example].number = 84
[Example].message = HELLO WORLD!
As a contradictory side note, in this question and answer, JetBrains' Engineer yole states that:
> "Declaring multiple properties on the same line is frowned upon by > many Java style guides, so we did not implement support for that in > Kotlin."
Note that his answer is more than 4-years old, so there could have been changes since then.
Solution 2 - Variables
Try this:
fun main() {
val (x, y, z) = listOf(1, true, "Sam") //can be "arrayOf(), "Pair()" or other types
println("$x, $y, $z")
}
Output:
1, true, Sam
Solution 3 - Variables
You might also find "Destructuring declarations" helpful here.
An example:
val (name, age) = person
More detail at https://kotlinlang.org/docs/destructuring-declarations.html.