Search code examples
kotlinguice

kotlin + aws lambda requiring empty constructor


I have the following class written in Kotlin+Guice that is invoked with a lambda

class LambdaProcessor @Inject constructor(private val s3Util: S3Util) {

    fun lambdaInvokesThisMethod() {
        s3Util.DoSomething()
    }
}

That works great for unit testing, but lambda requires the class to have an empty constructor.

I can convert this same class to have an empty constructor by doing this:

class LambdaProcessor {

    @Inject lateinit var s3Util: S3Util

    init {
        Guice.createInjector(GuiceDependencyInjector()).injectMembers(this)
    }

    fun lambdaInvokesThisMethod() {
        s3Util.DoSomething()
    }
}

That code now works great on lambda but I can't mock s3Util in my unit tests anymore because the init method gets called.

How can I get both scenarios to work together?


Solution

  • In Kotlin, if you have a default constructor then all your other constructors must call your default. But, you can have multiple constructors without a default constructor. Here is the final code we used.

    class LambdaProcessor {
    
        @Inject private lateinit var s3Util: S3Util
    
        /**
         * Lambda calls the no-arg constructor, use our IoC library to initialize our dependencies
         */
        constructor() {
            Guice.createInjector(GuiceDependencyInjector()).injectMembers(this)
        }
    
        /*
         * Unit-testing constructor
         */
        constructor(s3Util: S3Util) {
            this.s3Util = s3Util
        }
    
        fun lambdaInvokesThisMethod() {
            s3Util.DoSomething()
        }
    }