这可能太具体了,不能在这里发布,但我正在尝试使用kotlinpoet生成一个这样的类:
class Query<out E: Model>(val onSuccess: (E) -> Unit, val onError: (Int, String) -> Unit = { i, m -> })如何使用kotlinpoet创建类型/构造函数参数?docs确实有"Unit“类型和基本类型一起列出,所以它似乎是一个特例。
发布于 2017-08-02 08:30:16
这很容易通过使用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) {
}
}发布于 2017-08-03 15:24:56
下面是一个生成您需要的输出的程序:
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 -> })我在这里以out E的身份使用TypeVariableName,因为当时似乎没有更好的解决方案。我也在使用0.4.0-SNAPSHOT版本。
https://stackoverflow.com/questions/45449160
复制相似问题