'Default value for injection parameter

A simplified example:

I have the following Koin module:

val testModule = {
    factory<User> { (name: String) ->
        User(name)
    }
}

The User object can be injected with:

class TestClass {
   val user: User by inject() {
        parametersOf("John")
    }
}

However, I am wondering, is it possible to not provide a User parameter in TestClass? In that case, would it be possible to have a default name parameter set in the koin module's User factory?



Solution 1:[1]

First of all in your module use this :

val testModule = module{
    factory { (name: String) -> User(name) }
}

And about your second question , answer is yes you can provide it like this :

private val muser:User by inject()

In your case you can set your default value in your User model like this :

class User (name:String?="jack")

Solution 2:[2]

For anyone that comes across this in future, this was my solution, if you wrote the class that you want to create an instance of. This was tested on Koin 3.2.0-beta-1.

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.context.startKoin
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.dsl.module

fun main() {
    startKoin {
        modules(
            testModule
        )
    }

    val userComponent = UserComponent()
    println(userComponent.defaultUser.name)
    println(userComponent.namedUser.name)
}

class User(val name: String = "world")

val testModule = module {
    factory { User() }
    factory(named("named")) { (name: String) -> User(name) }
}

class UserComponent : KoinComponent {
    val defaultUser by inject<User>()
    val namedUser by inject<User>(named("named")) { parametersOf("Cloudate9") }
}

Output:

world
cloudate9

Explanation:
Kotlin supports default values for parameters. As such, we can define a default value for the name parameter in the User class, which will be used if we don't explicitly give name a value.

In the unnamed factory of User, we call it without an explicit name, and it thus uses the default value. In the named factory, we pass parameters to the factory to explicitly give name a value.

If the class was written by a third party, and there is no default value, replace the test module with this instead.

class User(val name: String) //Imagine this was created by a third party!

val testModule = module {
    factory { User("world") }
    factory(named("named")) { (name: String) -> User(name) }
}

That allows you to create a factory that you can default on if you don't want to provide params.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2