netimen
netimen

Reputation: 4419

How to declare several properties on one line

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?

Upvotes: 40

Views: 10419

Answers (4)

diskostu
diskostu

Reputation: 191

If you want to initialize multiple fields with the same value, you can do something like this:

val (x, y, z) = List(3) { 1 }

val (x, y, z) = List(3) { "Hello" }

and so on.

Upvotes: 1

Paulo Buchsbaum
Paulo Buchsbaum

Reputation: 2659

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.

Upvotes: 5

Stephan
Stephan

Reputation: 16729

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

Upvotes: 10

yole
yole

Reputation: 97148

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.

Upvotes: 61

Related Questions