-
When adding a property to a class, is there a way to use a type that you are generating as a property type? I am trying to generate the following: sealed interface ThingViewState {
object Idle : ThingViewState
}
class Thing {
private val _state = MutableStateFlow<ThingViewState>(ThingViewState.Idle)
val state = _state.asStateFlow()
} with the following: val name = "Thing"
FileSpec.builder("", name)
.addType(
TypeSpec.interfaceBuilder("${name}ViewState")
.addModifiers(KModifier.SEALED)
.addType(
TypeSpec.objectBuilder("Idle")
.addSuperinterface(ClassName("", "${name}ViewState"))
.build()
).build()
)
.addType(
TypeSpec.classBuilder(name)
.addProperty(
// Instead of Any::class, I want to use the "${name}ViewState" interface I'm generating above
PropertySpec.builder("_state", MutableStateFlow::class.parameterizedBy(Any::class))
.addModifiers(KModifier.PRIVATE)
.initializer("MutableStateFlow<${name}ViewState>(${name}ViewState.Idle)")
.build()
)
.addProperty(
PropertySpec.builder("state", StateFlow::class.parameterizedBy(Any::class))
.initializer("_state.asStateFlow()")
.build()
)
.build()
)
.build() When building the properties, is there a way I can use the interface I am generating? val ThingInterface = TypeSpec.interfaceBuilder("${name}ViewState")
PropertySpec.builder(
"_state",
MutableStateFlow::class.parameterizedBy(
// How do I tell it to use the type I generated in the file before?
ThingInterface::class
)
) Thanks for the help! |
Beta Was this translation helpful? Give feedback.
Answered by
shama
Nov 9, 2022
Replies: 1 comment
-
I just figured it out by guessing: val mutableStateFlowClass = ClassName("kotlinx.coroutines.flow", "MutableStateFlow")
val viewStateClass = ClassName("", "${name}ViewState")
PropertySpec.builder("_state", mutableStateFlowClass.parameterizedBy(viewStateClass)) so thank you for making an intuitive library! |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
shama
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just figured it out by guessing:
so thank you for making an intuitive library!