如何使用kotlinpoet生成带有单个类型参数的Kotlin“Unit”类型的构造函数参数?

这可能是有点太具体张贴在这里,但我想用kotlinpoet生成这样的类:

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

我将如何使用kotlinpoet创建该类型/构造函数参数? 文档确实有“ Unit ”类型与原始类型一起列出,所以它似乎是一个特例。

很简单,通过使用LambdaTypeName类来完成。 习惯了kotlin的功能类型风格,而不是java严格的功能接口,这有点令人困惑。 这是我用的:

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

这会产生(当然还有班级建设者):

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

这是一个产生你需要的输出的程序:

 class Model fun main(args: Array<String>) { val onSuccessType = LambdaTypeName.get( parameters = TypeVariableName(name = "E"), returnType = Unit::class.asTypeName()) val onErrorType = LambdaTypeName.get( parameters = listOf(Int::class.asTypeName(), String::class.asTypeName()), returnType = Unit::class.asTypeName()) val primaryConstructor = FunSpec.constructorBuilder() .addParameter(ParameterSpec.builder(name = "onSuccess", type = onSuccessType) .build()) .addParameter(ParameterSpec.builder(name = "onError", type = onErrorType) .defaultValue("{ i, m -> }") .build()) .build() val querySpec = TypeSpec.classBuilder("Query") .addTypeVariable(TypeVariableName(name = "out E", bounds = Model::class)) .addProperty(PropertySpec.builder(name = "onSuccess", type = onSuccessType) .initializer("onSuccess") .build()) .addProperty(PropertySpec.builder(name = "onError", type = onErrorType) .initializer("onError") .build()) .primaryConstructor(primaryConstructor) .build() val file = KotlinFile.builder(packageName = "", fileName = "test") .addType(querySpec) .build() file.writeTo(System.out) } 

这将打印(不包括生成的导入)以下内容:

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

我在这里攻击TypeVariableName ,因为当时似乎没有更好的解决方案。 我也使用0.4.0-SNAPSHOT版本。

Interesting Posts