what is the consensus on using local data classes?...
# getting-started
v
what is the consensus on using local data classes? yay or nay?
n
local, as in...defined inside a method? hm...I don't think I've ever done that
m
never done that… I can’t see the advantage at the moment
v
well; it beats Map<Triple<String, String, String>, T> in my case so blob shrug
m
of course, a custom type always beats primitive obsession and complex collections combination, just I can’t see why declaring one local, as “inside a method”…is that what you mean?
v
hmm
m
In general I think it would be cleaner to declare it as top-level in a file, you can even make it private if its scope is restricted to only classes/functions inside the file
v
so I had this case where I had a collection<T> where T had 10+ attributes; but each T is uniquely identified by T.a, T.b, T.c and a stupid bug I caused was due to me doing
val map = collection.associateBy { Triple(it.a, it.b, it.c) }
and then doing
map.keys.filter { it.first == x }
instead of `map.keys.filter { it.second == x }`; simplest way to avoid that seemed to be; in the context of the function;
val map = collection.associateBy { K(it.a, it.b, it.c) }
and then
map.keys.filter { it.b == x }
and given
K
was only needed in the context of said function, didn't need to be pulled out or exposed (even with
internal
) what I'm not sure of; if this is a "recommended" pattern
m
If you pull it up and mark it
private
it won’t be exposed anywhere. If I were to read code with local data types it would look less readable to me, but I guess it’a a matter of taste. There are no guidelines on this that I know of.
m
I would be fine with a local data class as long as the use for it seemed very specific to that function. I've never done it before, and I never used local classes in Java either. I always wind up feeling it is better to pull it up