Mapping some data to kotlin I sometimes find mysel...
# announcements
r
Mapping some data to kotlin I sometimes find myself doing something like this:
Copy code
data class A(
  val b: B
) {
  data class B(
    val c: C
  ) {
    data class C(
      val foo: String,
      val bar: Int
    )
  }
}
I find myself hankering after a more concise way of doing the same thing; something like:
Copy code
data class A(
  val b: data class B(
    val c: data class C(
      val foo: String,
      val bar: Int
    )
  )
)
I imagine those as being completely interchangeable - so the type of
A.b.c
is
A.B.C
. What do you think?
😱 1
🙈 2
t
I think you need Perl 😄
😄 2
n
My 0.02, I don't think the existing syntax is bad enough to justify adding this
C++/C have something similar to this in that they allow you to declare the type of the variable in the same line as the variable itself (though the resulting class is anonymous IIRC), and it's just not a really popular thing nowadays.
In terms of conciseness, it seems like really you're only saving repeating the dataclass name once, and a couple of newlines and braces
r
It’s not the saving in characters, it’s the form of the nesting. In the first I can see that A has a property b of type B, but I then have to go searching for a different point in the file for B’s declaration to see what properties a B has. Whereas in the second I can see immediately what properties b has; and the declaration even looks quite like the JSON or XML structure. (The example is obviously trivial, but of course XML and JSON are often quite deeply nested with lots of fields at each level of nesting.)
n
well, it's the same amount of nesting, either way, just changing where it is
i think it's hard to make a case for why this only makes sense in the primary constructor; if this were allowed then people would have use cases where they want it outside of that and they would justifiably ask why it can't be used outside of there.
So, this suggestion amounts to something pretty major; allowing the type after
:
to be either a type or a declaration of a type
👍 1
personally btw when I do this sort of thing I don't bother nesting the classes
r
I’m nesting the classes to try and reflect the nesting of the actual data; it feels to me that nesting them more obviously documents to the reader the format of the XML:
Copy code
<a>
  <b>
    <c>
      <foo>"hello"</foo>
      <bar>45</bar>
    </c>
  </b>
</a>
(Obviously if it’s reused in the structure you wouldn’t do it! But it’s pretty common to have single use structures, in my experience.)
n
I guess "more obviously" is the key phrase; the types of the members documents it anyhow. For me, I've preferred to allow that to document it (since it's what actually matters as well) and have the types at top level since it's more concise to refer to