'How to inject data class in android with dagger where data class parameter have no default value?
My data class like:
data class Animal(var id:Int = 2) {
}
My Provides method in module class like:
@Provides
@Singleton
fun provide(): Animal {
return Animal()
}
I want to avoid default value in data class parameter.
Solution 1:[1]
as per documentation while using data class primary constructor, it's must to pass at-least one parameter. remove data from class, after removing data there is no need to pass at-least single parameter to Constructor . hope this may helps you.
class Animal() {
var id:Int = 2
}
@Provides
@Singleton
fun provide(): Animal {
return Animal()
}
Solution 2:[2]
Just keep the fields nullable and assign them as null.
Class:
data class Animal @Inject constructor(
var id: Int? = null
) { }
Module:
@Provides
fun providesAnima(): Animal = Animal()
Solution 3:[3]
To avoid default value in parameter of data class you have to make it optional. In kotlin to make optional you have to use ? with the parameter.
data class Animal(var id:Int?=null) {
}
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 | Kaba |
Solution 3 | Ankita |