I have a weird situation and I was wondering if an...
# announcements
n
I have a weird situation and I was wondering if anyone has a solution. I have a couple data classes from a shared library that are structured very similarly.
Copy code
data class Foo(val width: Float, val height: Float, val x: Float, val y: Float)
data class Bar(val width: Float, val height: Float, val x: Float, val y: Float)
To construct them, I have to write something like
Copy code
when(clss) 
    is Foo -> constructFoo()
    is Bar -> constructBar()
with each of those construct methods doing the exact same thing (setting the same variable names & types). Is there a structure or something in Kotlin that I can use to make this cleaner?
k
Not really, there's always reflection as a last resort of course.
n
Yeah, that’s what I figured but I end up with a lot of repeating code so I figured I’d check
j
You could potentially use a method reference, e.g.
fun <T> construct(constructor: (Float, Float, Float, Float) -> T) = constructor(1f, 2f, 3f, 4f)
so then
constructFoo()
becomes
construct(::Foo)
. Not sure what constructFoo and constructBar do under the hood — if they do different things then they should probably be different methods! if they really do only differ by which constructor they call then this could be a way to reduce the duplication, but it’s also a bit more complicated so 🤷‍♂️ tradeoffs . . .
n
They’re copy-paste jobs with only the class being defined being the difference. I’ll play with this though! Thanks!