How to declare several properties on one line

2019-01-18 09:57发布

问题:

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?

回答1:

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.



回答2:

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


标签: kotlin