Reputation: 774
In kotlin, this is legal:
fun f1(): Int {
data class Data(val i: Int)
val d = Data(0)
return d.i
}
I wonder what are the consequenses of declaring a data class in a function. My best guess is that the data class is scoped to the function but I do not find anything in the doc mentionning that.
Upvotes: 1
Views: 676
Reputation: 4841
This is called Local Classes. They are mentioned in the documentation but only that they cannot have visibility modifiers.
You can take a look at Java's local classes for more information. It should be basically the same.
A typical use case is to have a throw-away implementation of some interface.
fun main() {
val f1 = f1()
println(f1.x)
println(f1.y)
}
interface Data {
val x : Int
val y : Int
}
fun f1(): Data {
data class SpecificData(override val x: Int, override val y: Int) : Data
return SpecificData(5, 10)
}
Upvotes: 4