Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Aliased import may throw java.lang.IllegalArgumentException if nullable and not nullable variants of it are used #2021

Open
mcarleio opened this issue Nov 14, 2024 · 0 comments
Labels

Comments

@mcarleio
Copy link
Contributor

Describe the bug
An aliased import added via addAliasedImport results in exception java.lang.IllegalArgumentException: Collection has more than one element if the type is used as nullable and as non-nullable.

To Reproduce

package org.example

import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.asTypeName

class PersonId

fun main() {
    println(
        FileSpec.builder("org.example", "SomeFile")
            .addAliasedImport(PersonId::class, "PID")
            .addFunction(
                FunSpec.builder("pid")
                    .returns(PersonId::class.asTypeName().copy(nullable = true))
                    .addCode("return %T()", PersonId::class)
                    .build()
            )
            .build()
    )
}

Expected behavior

package org.example

import org.example.PersonId as PID

public fun pid(): PID? = PID()

Actual behavior

Exception in thread "main" java.lang.IllegalArgumentException: Collection has more than one element.
	at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:605)
	at com.squareup.kotlinpoet.CodeWriter$Companion.withCollectedImports(CodeWriter.kt:740)
	at com.squareup.kotlinpoet.FileSpec.writeTo(FileSpec.kt:84)
	at com.squareup.kotlinpoet.FileSpec.toString(FileSpec.kt:222)
	at java.base/java.lang.String.valueOf(String.java:4465)
	at java.base/java.io.PrintStream.println(PrintStream.java:1187)
	at org.example.ExampleKt.main(Example.kt:10)
	at org.example.ExampleKt.main(Example.kt)

Additional context
When you change .addCode("return %T()", PersonId::class) to .addCode("return null") it works.
When you then add .addParameter("pid", PersonId::class), it breaks again.

Used version 2.0.0 above.
Worked with version 1.16.0.
Broken since 1.17.0.

Could be related to #2020

@mcarleio mcarleio added the bug label Nov 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant