I'm developing a class with several lateinit
properties of one type. I think it's too verbose to declare each of them on separate line like this:
lateinit var a: String
lateinit var b: String
so I would like to declare them on one line like this:
lateinit var b, c: String // error: Property getter or setter expected
But I get an error Property getter or setter expected
. Is there any way to declare several properties on one line in Kotlin?
Do not declare more than one variable per declaration. Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.
You can declare multiple variables in a single line. However, there are more efficient ways to define numerous variables in JavaScript. First, define the variables' names and values separated by commas using just one variable keyword from var , let or const.
In general, you should declare each variable on its own line with an explanatory comment regarding its role. While not required for conformance with this guideline, this practice is also recommended in the Code Conventions for the Java Programming Language, §6.1, “Number Per Line” [Conventions 2009].
To define multiple variables on a single line with JavaScript, we can use the array destructuring syntax. const [a, b, c, d] = [0, 1, 2, 3]; to assign a to 0, b to 1 , c to 2, and d` to 3 with the array destructuring syntax.
No, there is no way to do 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.
Looking at the grammar this is not possible:
property (used by memberDeclaration, declaration, toplevelObject) : modifiers ("val" | "var") typeParameters? (type "." | annotations)? (multipleVariableDeclarations | variableDeclarationEntry) typeConstraints ("by" | "=" expression SEMI?)? (getter? setter? | setter? getter?) SEMI? ;
You can only do destructing declarations with:
val (name, age) = person
You can use kotlin's destructuring declaration, but it doesn't work for lateinit
prefix.
var (a, b, c, d) = listOf("fly", 23, "slow", 28)
println("$a $b $c $d")
It is a workaround and creates unnecessary list initialization but it gets the job done.
Also you won't be able to define variable types yourself but the type inference is automatically done when using destructuring declarations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With