Data Model

data class AuthDataModel @Inject constructor(
                   var username: String = "",
                   var password: String = "",
                   var mobileData: String = "

解释

I am trying to inject authentication data model to authentication view model in kotlin, but it does not compile with message("Types may only contain one @Inject constructor)

推荐答案

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.

Kotlin相关问答推荐

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何为集成测试配置Gradle JVM测试套件?

为什么";";.equals(1)在柯特林语中是有效的,但";";=1是无效的?

创建包含 3 个相同项目的列表/使用返回类型重复

区分函数和扩展

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

我什么时候可以在 LazyList 或 Column 的范围内使用 Composable?

嵌套数组 indexOf()

使用纯 Kotlin 函数作为 Junit5 方法源

interface扩展

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

如何从不同的功能发出流量值? Kotlin 协程

Kotlin Compose,在行中对齐元素

为什么 Dialog 没有 NavController [Missing]?

无法在Kotlin中使用argb color int值?

在 Kotlin 中创建 Spinner 时,如何在 Fragment 中的旋转屏幕上修复指定为非空的参数为空?

Dagger +Kotlin 不注入

将字符串编码为Kotlin中的UTF-8

Android Kotlin .visibility

Kotlin - 错误:Could not find or load main class _DefaultPackage