Feature request for Kotlin

In Kotlin, nested classes are declared within another class, similar to the following example:

data class Information(
    val title: String,
    val subtitle: String,
    val summary: Summary
) {

    data class Summary(
        val imageUrl: String,
        val description: String
    )
}

In this example, Summary is a nested class within the Information class. While this syntax is concise and intuitive, it restricts developers to defining nested classes only within their enclosing class.

Alternative Syntax in Swift

In contrast, Swift offers a more flexible approach to nested class syntax. Developers can declare nested classes outside of their enclosing class, as demonstrated below:

struct Information {
    let title: String
    let subtitle: String
    let summary: Summary
}

extension Information {
    struct Summary {
        let imageUrl: String
        let description: String
    }
}

This alternative syntax in Swift provides developers with greater freedom in organizing their code and expressing relationships between classes. It allows for a more modular approach, particularly in scenarios where nested classes may be used across multiple contexts.

Proposal: Introducing Alternative Nested Class Syntax in Kotlin

Given the benefits of the alternative nested class syntax seen in Swift, it’s worth considering its integration into Kotlin. By introducing support for declaring nested classes outside of their enclosing class, Kotlin can offer developers enhanced flexibility and expressiveness in their code.

Here’s how the proposed syntax could look in Kotlin:

data class Information(
    val title: String,
    val subtitle: String,
    val summary: Summary
)

data class Information.Summary(
    val imageUrl: String,
    val description: String
)

With this syntax, Kotlin developers would have the option to choose between nesting classes within their enclosing class or declaring them independently. This flexibility can lead to cleaner and more modular code, facilitating code reuse and improving maintainability.

See this proposal

Presumably the same solution should also apply to defining a companion object outside the class it’s companion to?