Moving my comment to an answer:
如果你有一个带有默认参数的构造函数,Kotlin实际上会生成额外的构造函数.在您的例子中,有一个3参数构造函数,其中所有参数都是可选的,它总共生成4个构造函数.Kotlin显然会将主构造函数上的任何注释与所有生成的注释关联起来,这意味着最终会有4@Inject
个构造函数.
您有两个 Select :
The first, as you mentioned yourself, remove all the default values. If there are no default values, only one constructor is generated with the annotation.
或者,您也可以自己创建其他构造函数,并将其指向主构造函数.这还可以让您手动指定只有一个具有@Inject
注释,而其他注释不具有@Inject
注释.基本上:
data class AuthDataModel @Inject constructor(
var username: String,
var password: String,
var mobileData: String) {
constructor(username: String) : this(username, "", "") {}
constructor(username: String, password: String) : this(username, password, "") {}
}
不使用默认值会阻止生成多个@Inject构造函数,并且辅助构造函数应该1保持一切按预期运行.这基本上是重载构造函数,当某些变量是可选的时,这相当于在Java中所做的.因此应该没问题.
1: I haven't done Android in a while, and I've never used @Inject. If option 2 doesn't work (as in @Inject doesn't allow it, or doesn't work as expected, etc.), that only leaves option 1, and requires every parameter to be explicitly passed. The secondary constructors calling the primary constructor should be enough to keep everything working, though.