Limitations for data class declaration?


#1

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?

Cheers,
Christian


#2

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


#3

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 …


#4

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