Limitations for data class declaration?


Usual classes can be deklared inside other classes or inside functions/methods. This is not the case for data classes. The following snippet doesn't compile:

fun main(args : Array<String>) {
  data class User(val name: String, val age: Int)

Where the following was compiled without errors:

fun main(args : Array<String>) {
  class User(val name: String, val age: Int)

I tried it with the “Kotlin Web Demo”.

Is this a bug or an undocumented limitation?



In local scopes, use brackets around annotations: [data]


Thanks for the quick and helpful answer.

It wasn’t obvious to me that “data” is an annotation. Maybe this sould be mentioned on the data class documentation page.

Wouldn’t it be possible to make the compiler work without []? It is some of these little special cases you have to keep in your mind …


It would be at least rather non-trivial to make it work without the []