diff --git a/docs/changelog.md b/docs/changelog.md index 89f276f3b..785d5fac4 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -9,6 +9,7 @@ Change Log Change: kotlinx-metadata 0.9.0. Note that the `KotlinClassMetadata .read` is deprecated in 0.9.0 and replaced with `readStrict` (#1830). * Fix: `KSAnnotation.toAnnotationSpec` writes varargs in place instead of making them an array to work around a Kotlin issue with `OptIn` annotations (#1831). +* Fix: `MemberName`s without a package are now correctly imported (#1841) ## Version 1.16.0 diff --git a/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt b/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt index 2c2af76e0..4921c59a9 100644 --- a/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt +++ b/kotlinpoet/src/commonMain/kotlin/com/squareup/kotlinpoet/CodeWriter.kt @@ -514,12 +514,10 @@ internal class CodeWriter constructor( } private fun importableMember(memberName: MemberName) { - if (memberName.packageName.isNotEmpty()) { - val simpleName = imports[memberName.canonicalName]?.alias ?: memberName.simpleName - // Check for name clashes with types. - if (memberName.isExtension || simpleName !in importableTypes) { - importableMembers[simpleName] = importableMembers.getValue(simpleName) + memberName - } + val simpleName = imports[memberName.canonicalName]?.alias ?: memberName.simpleName + // Check for name clashes with types. + if (memberName.isExtension || simpleName !in importableTypes) { + importableMembers[simpleName] = importableMembers.getValue(simpleName) + memberName } } diff --git a/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/MemberNameTest.kt b/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/MemberNameTest.kt index 69271d7df..83fb870da 100644 --- a/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/MemberNameTest.kt +++ b/kotlinpoet/src/commonTest/kotlin/com/squareup/kotlinpoet/MemberNameTest.kt @@ -542,6 +542,29 @@ class MemberNameTest { ) } + @Test fun importMemberWithoutPackage() { + val createTaco = MemberName("", "createTaco") + val file = FileSpec.builder("com.example", "Test") + .addFunction( + FunSpec.builder("makeTacoHealthy") + .addStatement("val taco = %M()", createTaco) + .build(), + ) + .build() + assertThat(file.toString()).isEqualTo( + """ + |package com.example + | + |import createTaco + | + |public fun makeTacoHealthy() { + | val taco = createTaco() + |} + | + """.trimMargin(), + ) + } + // https://github.com/square/kotlinpoet/issues/1089 @Test fun `extension MemberName imported if name clash`() { val hashCode = MemberName("kotlin", "hashCode", isExtension = true)