Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define multiple variables at once in Kotlin (e.g Java : String x,y,z;)

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; 
like image 427
Seaskyways Avatar asked Nov 02 '16 17:11

Seaskyways


People also ask

How do you declare multiple variables at the same time in Java?

Declaring and Assigning Variables You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b .

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


1 Answers

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 (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) } 

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.

like image 88
marcelovca90 Avatar answered Sep 16 '22 13:09

marcelovca90