https://kotlinlang.org logo
Title
n

Nick Tiller

06/13/2019, 10:14 PM
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.
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
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

karelpeeters

06/13/2019, 10:20 PM
Not really, there's always reflection as a last resort of course.
n

Nick Tiller

06/13/2019, 10:35 PM
Yeah, that’s what I figured but I end up with a lot of repeating code so I figured I’d check
j

Jordan Stewart

06/14/2019, 7:53 AM
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

Nick Tiller

06/14/2019, 4:49 PM
They’re copy-paste jobs with only the class being defined being the difference. I’ll play with this though! Thanks!