kotlinpoet

How to prevent importing class defined in the same file?


I need the following generated code:

import DoesntMatter

class MyClass {}

fun DoesntMatter.function(i: MyClass.() -> Unit) {}

I have written the following:

FunSpec.Builder funBuilder = FunSpec.builder(funName);
funBuilder.receiver(new ClassName("", "DoesntMatter")); // ok, i need that import
funBuilder.addParameter("i", LambdaTypeName.get(
  new ClassName("", "MyClass"), // i do not need that import cause i declare this class in my file
  new ArrayList<>(),
  TypeNames.UNIT));

TypeSpec.Builder typeBuilder = TypeSpec.classBuilder("MyClass"); // here i declare class

FileSpec.Builder fileBuilder = FileSpec.builder(packageName, model.getName())
  .addType(typeBuilder.build())
  .addFunction(funBuilder.build());

But it generates import that i dont need:

import DoesntMatter
import MyClass

class MyClass {}

fun DoesntMatter.function(i: MyClass.() -> Unit) {}

And i get compile error. Workaround is to split function declaration and class declaration into two different files, but it is not really pretty as intented.

Is there any hack to not produce uselss import or where is my code wrong?


Solution

  • Here's the output I get when running your code with packageName == "":

    import kotlin.Unit
    
    public class MyClass
    
    public fun DoesntMatter.function(i: MyClass.() -> Unit) {
    }
    

    Neither MyClass nor DoesntMatter are imported, since they're in the same package.

    And here's what I get when I set packageName to a non-empty string, e.g. com.squareup.kotlinpoet:

    package com.squareup.kotlinpoet
    
    import DoesntMatter
    import MyClass
    import kotlin.Unit
    
    public class MyClass
    
    public fun DoesntMatter.function(i: MyClass.() -> Unit) {
    }
    

    Both types are imported, since they're declared in a different package than this file. You're basically redeclaring MyClass in this file, but referencing the one in the default package in your function declaration, since the correct ClassName for this one is ClassName("com.squareup.kotlinpoet", "MyClass").

    So make sure the package names check out to avoid unwanted imports. KotlinPoet treats packageName == "" as "default package", not "same package", so you can't rely on omitting the package name to avoid an import.

    Also, please make sure you're using the latest version of the library, which is 1.15.3 at the time of writing.