使用 Room 构建时出错:kapt 发生异常:java.lang.IllegalArgumentException:voidcannot be converted to an Element

Error when building with Room: kapt An exception occurred: java.lang.IllegalArgumentException: voidcannot be converted to an Element

在构建使用 Room 库、用于依赖注入的 Dagger 和 Kotlin 的项目时,我遇到了这个错误:

[kapt] An exception occurred: java.lang.IllegalArgumentException: voidcannot be converted to an Element

这是我的代码:

@Entity(tableName = "contacts_table")
data class Contact(@PrimaryKey var cid: Long,
          @ColumnInfo(name = "firstColor") var firstColor: String?,
          @ColumnInfo(name = "secondColor") var secondColor: String?,
          @ColumnInfo(name = "avatarUrl") var avatarUrl: String?,
          @ColumnInfo(name = "name") var name: String,
          @ColumnInfo(name = "nickname") var nickname: String)


@Dao
interface ContactsDao {

     @Insert(onConflict = REPLACE)
     fun insertContact(contact: Contact)

     @Query("delete from contacts_table where cid=:id")
     fun deleteContactById(id: Long)

     @Query("select * from contacts_table")
     fun getAllContacts() : List<Contact>
}


@Database(entities = [Contact::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
     abstract fun contactsDao()
}

这是我如何使用 DAO 的示例:

contactsDao.insertContact(Contact(response.id, response.firstColor, response.secondColor, 
        null, response.name, response.nickname)) 

contactsDao.insertContact(Contact(response.id, null, null, response.avatarUrl, 
        response.name, response.nickname))

如何修复此构建错误?

在您的 AppDatabase 中,您必须为 contactsDao() 指定 return 类型。必须是 ContactsDao。因此,您的 class 应如下所示:

@Database(entities = [Contact::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
     abstract fun contactsDao(): ContactsDao
}