有多个好的构造函数,Room将选择no-arg构造函数.如何解决这个警告 [英] There are multiple good constructors and Room will pick the no-arg constructor. How to solve this warning

查看:1570
本文介绍了有多个好的构造函数,Room将选择no-arg构造函数.如何解决这个警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在android kotlin项目中实现Room Persistent Database库,但在编译时收到此警告.我不知道如何解决这种冲突.

I try to implement Room Persistent Database library in android kotlin project, but catch this warning at compile time. I don't know how to solve this warring.

警告:有多个优秀的构造函数,Room会选择 无参数构造函数.您可以使用@Ignore注释消除 不需要的构造函数.

warning: There are multiple good constructors and Room will pick the no-arg constructor. You can use the @Ignore annotation to eliminate unwanted constructors.

自动生成的类

public final class Gender {
             ^

科特林数据类

import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey

@Entity
data class Gender(@PrimaryKey(autoGenerate = true)
             var genderId: Int = 0,
             var type: String = "")

推荐答案

这里的问题"是kotlin正在为您的类生成多个构造函数,假设您具有某些属性的默认参数.

The "problem" here is that kotlin is generating multiple constructors for your class, given that you have default parameters for some of the properties.

您的情况是:

// this is the synthetic one, don't worry to much about it
public Gender(int var1, String var2, int var3, DefaultConstructorMarker var4) { /* some implementation */ }

// the "default" one, that can be called when you are delegating to the default params
public Gender() { /* some implementation */ }

// the one that gets all the params
public Gender(int genderId, @NotNull String type) { /* some implementation */ }

房间可以使用不带参数的一个,也可以使用带两个参数的一个,并选择其中一个(并通过warning告知您)

Room could be using either the one without parameters, or the one with two, and it's choosing one of them (and letting you know via that warning)

您可以删除type的默认参数,并且只有一个(非合成的)构造函数:

You can remove the default parameter for type, and there will be only one (non-synthetic) constructor:

// still synthetic
public Gender(int var1, String var2, int var3, DefaultConstructorMarker var4) { /* some implementation */ }

// this is the only usable constructor now
public Gender(int genderId, @NotNull String type) { /* some implementation */}

现在Room仅使用一个构造函数,因此它将很高兴地使用它.

Now Room has only one constructor to use, so it will use it happily.

如果用例允许,则可以删除默认值.请注意,您只能对非原始类型执行此操作,这会使您的API更美观.

If your use case allows it, you can just remove the default values. Note that you could only do it for the non-primitive types, which make make your API nicer.

我不知道您的特殊情况,但请注意,您也可以使用val代替var

I don't know about your particular case, but note that you could also use val instead of var

@Entity
data class Gender(
    @PrimaryKey(autoGenerate = true)
    val genderId: Int = 0,  // so callers don't need to specify an id. Room will generate one if it gets a 0 here
    var type: String
)

这篇关于有多个好的构造函数,Room将选择no-arg构造函数.如何解决这个警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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