https://kotlinlang.org logo
#getting-started
Title
# getting-started
v

vineethraj49

01/28/2021, 8:08 PM
what is the consensus on using local data classes? yay or nay?
n

nanodeath

01/28/2021, 8:10 PM
local, as in...defined inside a method? hm...I don't think I've ever done that
m

Matteo Mirk

01/29/2021, 8:55 AM
never done that… I can’t see the advantage at the moment
v

vineethraj49

01/29/2021, 8:56 AM
well; it beats Map<Triple<String, String, String>, T> in my case so blob shrug
m

Matteo Mirk

01/29/2021, 8:58 AM
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

vineethraj49

01/29/2021, 8:59 AM
hmm
m

Matteo Mirk

01/29/2021, 9:01 AM
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

vineethraj49

01/29/2021, 9:03 AM
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

Matteo Mirk

01/29/2021, 11:29 AM
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

mkrussel

01/29/2021, 1:04 PM
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