类型只能包含一个@Inject构造函数 [英] Types may only contain one @Inject constructor

查看:151
本文介绍了类型只能包含一个@Inject构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

说明

我正在尝试将身份验证数据模型注入kotlin中的身份验证视图模型,但是它不能与message一起编译(类型只能包含一个@Inject构造函数)

Explanation

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)

推荐答案

将我的评论移至答案:

如果您具有带有默认参数的构造函数,那么Kotlin实际上会生成其他构造函数.在您的情况下,您有3个arg构造函数,其中所有都是可选的,总共生成4个构造函数. Kotlin显然还将主构造函数上的所有注释也与所有生成的注释相关联,这意味着您最终得到了4个@Inject构造函数.

If you have a constructor with default arguments, Kotlin actually generates additional constructors. In your case, you have a 3 arg constructor where all are optional, which generates a total of 4 constructors. Kotlin apparently associates any annotations on the primary constructor with all the generated ones as well, which means you ended up with 4 @Inject constructors.

您有两个选择:

第一个,正如您自己提到的,删除所有默认值.如果没有默认值,则仅使用注释生成一个构造函数.

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注释,而其他人则没有.基本上:

Alternatively, you can also create additional constructors yourself and point it to the primary. This would also let you manually specify only one to have the @Inject annotation, while the others don't. Basically:

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中所做的事情.因此应该没问题.

Not using default values prevents multiple @Inject constructors from being generated, and the secondary constructors should1 keep everything functioning as expected. This is basically overloading the constructor, and it's equivalent to what you'd do in Java when certain variables are optional. Should therefore be fine.

1:我已经有一段时间没有使用Android了,而且我从未使用过@Inject.如果选项2不起作用(如@Inject不允许,或不能按预期方式工作,等等),则仅保留选项1,并要求显式传递每个参数.但是,调用主构造函数的辅助构造函数应该足以保持一切正常.

这篇关于类型只能包含一个@Inject构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆