Skip to content

Commit

Permalink
Constructor properties
Browse files Browse the repository at this point in the history
  • Loading branch information
deotimedev committed Dec 28, 2022
1 parent 0f50ec3 commit 5b30635
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/main/kotlin/me/deotime/kpoetdsl/TypeBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import kotlin.reflect.KClass

class TypeBuilder private constructor(private val cozy: Cozy<TypeBuilder>) :
Attributes.Sourced<TypeSpec.Builder>,
Attributes.Buildable<TypeSpec> by Attributes.buildWith(cozy, TypeSpec.Builder::build),
Attributes.Buildable<TypeSpec>,
Attributes.Has.Functions by Attributes.functionVisitor(cozy, TypeSpec.Builder::addFunction),
Attributes.Has.Properties by Attributes.propertiesVisitor(cozy, TypeSpec.Builder::propertySpecs),
Attributes.Has.Type.Parameters by Attributes.parameterizedTypeVisitor(cozy, TypeSpec.Builder::typeVariables),
Expand All @@ -28,6 +28,8 @@ class TypeBuilder private constructor(private val cozy: Cozy<TypeBuilder>) :
override val source by withRequired { kind.init(if (kind == Type.Selector.Anonymous) "no-op" else name) }
private var kind by required<Type>()

private val primaryConstructor = FunctionBuilder.cozy()

fun kind(selector: Type.Selector.() -> Type) {
kind = selector(Type.Selector)
}
Expand All @@ -36,6 +38,16 @@ class TypeBuilder private constructor(private val cozy: Cozy<TypeBuilder>) :
source.primaryConstructor(FunctionBuilder.cozy().buildWith(assembler))
}

fun constructorProperty(assembler: Assembler<PropertyBuilder>) {
val prop = PropertyBuilder.cozy().buildWith {
assembler()
initializer { +name }
}
primaryConstructor.parameter(prop.name) {
type(prop.type)
}
}

fun initializer(assembler: Assembler<CodeBuilder>) {
source.addInitializerBlock(CodeBuilder.cozy().buildWith(assembler))
}
Expand All @@ -60,6 +72,11 @@ class TypeBuilder private constructor(private val cozy: Cozy<TypeBuilder>) :

inline fun <reified T> implement() = implement(T::class.asTypeName())

override fun build() =
source.apply {
primaryConstructor.build().takeIf { it.parameters.isNotEmpty() }?.let { primaryConstructor(it) }
}.build()

@JvmInline
value class Type private constructor(val init: (String) -> TypeSpec.Builder) {
object Selector {
Expand Down

0 comments on commit 5b30635

Please sign in to comment.