[Feature Request] Inner Objects

#1

I noticed today that, while Kotlin supports inner classes, it does not support inner objects. The way I would imagine this to work is:

class ApiGateway{

    fun put(url:String, body: String): String { ... }
    fun get(url: String): String{ ... }
    private fun toJson(obj: Any): String { ... }
    
    inner object LoggingClient {
 
        fun logError(m: Message, e: Exception) {
            this@ApiGateway.post("my-awesome-logging-endpoint", toJson(e))
        }
         
    }
}

This would be equivalent to:

class ApiGateway{

    fun put(url:String, body: String): String { ... }
    fun get(url: String): String{ ... }
    private fun toJson(obj: Any): String { ... }
    
    // resolve the "inner object" to a field of the appropriate type, and an inner class
    val loggingClient = LoggingClient()

    inner class LoggingClient {
        fun logError(m: Message, e: Exception) {
            this@ApiGateway.post("my-awesome-logging-endpoint", toJson(e))
        }
    }
}

The entire point here is to be able to call it like this:

this.apiGateway.loggingClient.logError("whoops", exception)

It’s a small thing, but I believe it could be quite useful, in particular for DSL building.

#2

You can use

class Foo {
   val bar = object {}
}
2 Likes