I think there was some discussion of this earlier ...
# compiler
r
I think there was some discussion of this earlier - is there any proposal to make anonymous objects have an associated type capturing their members?
I'd like to be able to type
user.links.self
and it compile for this class:
Copy code
data class User(val id: Id) {
  val links = object {
    val self = "/v1/users/$id"
  }
}
As it is I'm doing this:
Copy code
data class User(val id: Id) {
    val links = Links(
        self = "/v1/users/$id"
    )
    data class Links(
        val self: String
    )
}
which works fine but feels & reads slightly more laborious.
h
Or use an inner class:
Copy code
data class User(val id: Long) {
    val links = Links()

    inner class Links {
        val self = "/v1/users/$id"
    }
}
Or an interface
r
That's less noisy, thanks.
e
If you want something composable.. maybe overkill.. I'm a big fan of how easy it is to compose behaviour with delegation 🙂
Copy code
data class User(val id: Id): Linkable<Links.Self> by selfLink("/v1/users/$id")

interface Linkable<T : Links> {
  val links: T
}

sealed interface Links {
  data class Self(val self: String) : Links
}

fun selfLink(path: String) = object : Linkable<Links.Self> { override val links = Links.Self(path) }
e
There was a similar discussion elsewhere recently, let me find it.
That was about "inner object".
Maybe we should support "inner object", indeed.
r
Thanks, sorry my searching was weak.
And I am in the wrong channel... apologies
e
Fully onboard with inner object 🐕 Looking forward to seeing it in a coming features survey
Add your use-cases that that issue, please.
g
I believe there is also discussion about case when you don’t necessary need internal object, but just an exposed object like:
Copy code
object Dependencies {
   val ktor = object {
           val core = …
           val auth = …
   }
}
to allow use it like
Dependencies.ktor.auth
It’s probably has the same issues as internal in terms of that it requires some object name generation. I would be probably would be fine if it would be required to use named object like: val ktor = object Ktor {} So no class name generation requied
e
Exposing object also requires us to generate a stable class name under the hood. And the rules on how this name is derived and when you can count on it being stable are going to be quite complicated. From this angle, it looks easier to simply support
inner object
for such a use-cases.
g
Ah, indeed, inner object a lot easier because of jvm internal classes convention, yeah, for case which I shared above inner class also perfectly works