这是一个产生您需要的输出的程序:
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
这里进行黑客攻击out E
,因为当时似乎没有更好的解决方案。我也在用这个0.4.0-SNAPSHOT
版本。