kotlinkotlinpoet

How should I form a list property type with my own type


I am trying to form below final kotlin code

val participants: List<AbstractParty>

I tried to use below code in kotlinpoet but it shows error, I think it is not correct, but don't know how should I fix it. Any one can help? Thanks.

PropertySpec.builder("participants", List<ClassName("AbstractParty">)

Solution

  • Depending on whether you have a reference to a class or if you need to create its name from Strings, you can do either this:

    PropertySpec.builder("participants",
         ParameterizedTypeName.get(List::class, AbstractParty::class)
    ).build()
    

    Or this:

    PropertySpec.builder("participants",
        ParameterizedTypeName.get(
                List::class.asClassName(),
                ClassName("some.pckg.name", "AbstractParty"))
    ).build()
    

    A hint to finding out these sorts of things: KotlinPoet has pretty extensive tests, you can find examples of almost anything in there.