1

I'm new to KotlinPoet and I cannot find how to create the following Koin module statement:

internal val apiModules = module {
    single<Name1> { get<Retrofit>().create(Name1::class.java) }
    single<Name2> { get<Retrofit>().create(Name2::class.java) } 
}

directly into a Kotlin file (no wrapper class)

I have been playing around with PropertySpec and CodeBlock but I don't know how to import Koin DSL or how to reference those imported classes in the code generation. I was also unable to generate the code by pure string generation.

m0skit0
  • 25,268
  • 11
  • 79
  • 127

1 Answers1

5

You need to generate the file using FileSpec and add a PropertySpec for the module

It shold look similar to this

val moduleClassName = ClassName("org.koin.core.module.Module", "Module") //This will take care of the import

val moduleMemberName = MemberName("org.koin.dsl.module", "module") //This will take care of the import

val moduleInitilizerCodeBlock = 
    CodeBlock.Builder()
        .beginControlFlow("%M", moduleMemberName) //This will take care of the {} and indentations 
        .addStatment(ADD ANOTHER CODE BLOCK SIMNILAR TO THIS FOR THE SINGLE/FACTORY)
        .endControlFlow()
        .build()

val module = PropertySpec.builder("YOUR MODULE NAME", moduleClassName)
        .initializer(moduleInitilizerCodeBlock)
        .build()

FileSpec.Builder("FILE PACKAGE", "FILE NAME")
       .addProperty(module)
       .build()

This is not full code but it should point you in the right direction. Side note: I might me wrong about specific namings but again it should be enough

Gil Goldzweig
  • 1,809
  • 1
  • 13
  • 26
  • Very nice, thanks a lot. I got it working, however the `FunSpec.Builder("FILE PACKAGE", "FILE NAME")` does not compile, you might want to edit that. I guess you wanted `FileSpec` instead. – m0skit0 May 23 '19 at 09:53
  • Awesome, I did mean File I will fix it – Gil Goldzweig May 23 '19 at 10:15