Search code examples
variableskotlin

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;

Solution

  • 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.