Search code examples
jvmkotlintemplate-meta-programmingkotlinpoet

How do I generate a constructor parameter of the Kotlin "Unit" type with a single type parameter with kotlinpoet?


This might be a bit too specific for posting here, but I'm trying to generate a class like this with kotlinpoet:

class Query<out E: Model>(val onSuccess: (E) -> Unit, val onError: (Int, String) -> Unit = { i, m -> })

How would I create that type/constructor parameter with kotlinpoet? The docs do have the "Unit" type listed along with primitive types, so it seems to be a special case.


Solution

  • Easily enough, it's done by using the LambdaTypeName class. It was a bit confusing after getting used to kotlin's functional type style as opposed to java strictly functional interfaces. Here's what I used:

    val typeVariable = TypeVariableName.invoke("E")
        .withBounds(QueryData::class)
    ParameterSpec.builder("onSuccess", 
        LambdaTypeName.get(null, listOf(typeVariable), UNIT)).build()
    

    Which generates (with the class builders, of course):

    class Query<E : QueryData> {
      constructor(onSuccess: (E) -> Unit) {
      }
    }