How to implement a functional interface? #2348
|
I'm having issues writing implementations for functional interfaces Let me use a simple example, given this example functional interface: val getFooClassname = ClassName("com.example.funintest", "GetFoo")
FileSpec.builder(getFooClassname)
.addType(
TypeSpec.funInterfaceBuilder("GetFoo")
.addFunction(
FunSpec
.builder("execute")
.addModifiers(KModifier.SUSPEND, KModifier.ABSTRACT)
.addParameter("id", String::class)
.addParameter("page", Int::class)
.returns(String::class)
.build(),
)
.build(),
)
.build()
.writeTo(baseDir)it outputs as expected: public fun interface GetFoo {
public suspend fun execute(id: String, page: Int): String
}How would I write in poet an implementation for it? Something to output like this here: fun getFoo(): GetFoo = GetFoo { id: String, page: Int ->
// some more code
"42"
}The main issue for me is to put the parameters after the lambda (in the example Here is what I got: .addFunction(
FunSpec
.builder("getFoo")
.returns(getFooClassname)
.beginControlFlow("return %T", getFooClassname)
.addCode("id: String, page: Int? ->\n") // <<<<< THIS HERE hard coded instead of properly parametrized
.addCode("// some more code\n") // just example ignore the contents
.addCode("\"42\"\n") // just example ignore the contents
.endControlFlow()
.build(),
)which outputs this: public fun getFoo(): GetFoo = GetFoo {
id: String, page: Int? -> // UGLY parameters in the next line, technically compiles but maybe there's a better way?
// some more code
"42"
}Any help? |
Replies: 1 comment 2 replies
|
and exactly 15 minutes after opening this question I found an improved version, still not sure if this is "the way". Is that the proper way of doing it? |
There is no real proper way. Using control flow is a bit of a hack, but it works. You could also manually use indent control to inset the body of the lambda.
We probably need some helper here, but it's never been massively pressing to create.