carbaj0
08/06/2023, 11:51 AM@OptIn(ExperimentalTypeInference::class)
suspend operator fun <A> Person.Companion.invoke(
initialState: A,
@BuilderInference f: suspend context(Copy<A>, Person.Companion) () -> Unit
): Flow<A> =
CopyImpl(initialState).also { f(it, this) }.state
Do you think this function can be generic?
I mean, can I make the Companion generic?
@OptIn(ExperimentalTypeInference::class)
suspend operator fun <A , B> B.Companion.invoke(
initialState: A,
@BuilderInference f: suspend context(Copy<A>, B.Companion) () -> Unit
): Flow<A> =
CopyImpl(initialState).also { f(it, this) }.state
something like this?raulraja
08/06/2023, 1:31 PMA
there is a generic thing called Companion
. This currently does not exist in Kotlin and it's not possible to make such functions generic unless you resort to metaprogramming or reflection tricks to implement it in Kotlin. Currently companion
objects are not able to be abstracted away with generics because there is no superclass for all companions that isn't Any?
.
You can of course define a common interface that all companions implement on which you project your functions to avoid reimplementing them ad-hoc.
@OptIn(ExperimentalTypeInference::class)
suspend operator fun <A> CompanionInterface.invoke(
initialState: A,
@BuilderInference f: suspend context(Copy<A>, CompanionInterface) () -> Unit
): Flow<A> =
CopyImpl(initialState).also { f(it, this) }.state
companion object : CompanionInterface { ... }
This isn't trivial as the copy methods may be code generated specifically for Person or other target type you use in generation.