Momh
Momh

Reputation: 774

Kotlin allows defining data class in a function, why?

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

Answers (1)

Januson
Januson

Reputation: 4841

This is called Local Classes. They are mentioned in the documentation but only that they cannot have visibility modifiers.

  • You cannot access local class anywhere outside of the function it was declared in.
  • It can access any members, including private members, of the containing class.
  • It can access any local variables or method parameters that are in the scope of the declaring function

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

Related Questions