square / kotlinpoet

A Kotlin API for generating .kt source files.
https://square.github.io/kotlinpoet/
Apache License 2.0
3.92k stars 289 forks source link

Get exception tying to generate empty fun interface which inherit another interface with exact one abstract function #1972

Open jizoquval opened 2 months ago

jizoquval commented 2 months ago

Describe the bug Using KotlinPoet 1.18.1 I get the exception: java.lang.IllegalStateException: Functional interfaces must have exactly one abstract function. Contained 0: [] when try to generate valid kotlin code. I'm trying to generate functional interface which doesn't contains new methods and inherits another functional interface with method declaration.

To Reproduce

    val bClassName = ClassName("","B")
    val aClassName = ClassName("","A")
    val fileSpec = FileSpec.builder("", "Example")
        .addType(
            TypeSpec.funInterfaceBuilder(bClassName)
                .addFunction(
                    FunSpec.builder("foo")
                        .addModifiers(KModifier.ABSTRACT)
                        .build(),
                )
                .build()
        )
        .addType(
            TypeSpec.funInterfaceBuilder(aClassName)
                .addSuperinterface(bClassName)
                .build()
        )
        .build()
    fileSpec.writeTo(System.out)

Expected behavior I expect to get generated code instead of exception.

Additional context This is a correct kotlin code and it can be compiled.

fun interface A: B

fun interface B {
  fun foo()
}
Egorand commented 2 months ago

Does the compiler check that B is a functional interface, or an interface that has exactly one method?

But given that KotlinPoet's correctness checks don't have to be as exhaustive as the real compiler's, I think we can allow zero methods in a functional interface if it has a superinterface. Would that make sense?

PRs welcome!

jizoquval commented 2 months ago

@Egorand B can be a simple interface, not fun interface. As I understand the compiler only checks that B has exact one method.

Yes, I think such solution will make sense

jizoquval commented 2 months ago

I can try to fix it and open PR.