https://kotlinlang.org logo
t

thana

06/09/2020, 10:07 AM
Hi, i have some class like
class Foo<T> (val helper1: Helper1<T>, helper2: Helper2<T>)
. here i want
Helper1
and
Helper2
work on the same type
T
but in fact
Foo
doesn't really care about what
T
actually is - they just must match. Is there a way not having to declare the
T
on
Foo
itself? I don't want to write something like
Foo<*>
everywhere i'm using
Foo
Or maybe the better question: i sense there is some design flaw here but i cannot really put the finger on. What approaches are there, to resolve this flaw?
e

E.Kisaragi

06/09/2020, 10:15 AM
don't you want Foo to have generic type T, right?
t

thana

06/09/2020, 10:17 AM
Foo
shouldn't be generic
e

E.Kisaragi

06/09/2020, 10:18 AM
you may try this: class Foo { companion object { operator fun <T> invoke(help1: Helper1<T>,help2: Helper2<T>): Foo = TODO("logic") } }
and Foo(helper1, helper2)
t

thana

06/09/2020, 10:21 AM
but then, how do i declare the fields
helper1
and
helper2
?
d

dead.fish

06/09/2020, 10:22 AM
The invoke operator above acts as factory, you add them to some private constructor where your args become
Helper<Any>
after all,
Foo
shouldn’t care about the `Helper`s generic args, right?
t

thana

06/09/2020, 10:23 AM
ah good point
i dpo not realy like the
Any
approach, but at least it's a small improvement... i hope 😉 Thank you so far!
still i feel there is something wrong with that approach as a whole. any ideads on that?
l

Luis Mirabal

06/09/2020, 10:52 AM
A little bit more context would help. I t depends what role do the helpers play in Foo. If they’re dependencies and Foo can’t perform its responsibilities without them, it would make sense that Foo includes the generic type. If the helpers play a secondary role, maybe a type wrapping them and serving as a facade make sense, and then that new type can include the generic info