我的Android应用程序有一个Room数据库。我的FooDao和BarDao都实现了BaseDao:
interface BaseDao{ @Insert fun insert(obj: T): Long @Update fun update(obj: T) } @Dao interface FooDao: BaseDao { @Query("some query") fun doSomethingWithFoo() } @Dao interface BarDao: BaseDao { @Query("some other query") fun doSomethingWithBar() }
我也有一个存储库类:
class MyRepo(private val fooDao: FooDao, private val barDao: BarDao) { fun doSomethingWithFoo() = fooDao.doSomethingWithFoo() fun doSomethingWithBar() = barDao.doSomethingWithBar() }
但是,可以想象FooDao,BarDao和MyRepo不仅具有这两个功能。
我已经了解了有关类委托以启用组合继承的知识。因此,我试图通过让MyRepo委托简单的函数来减少MyRepo的样板,这些简单函数仅调用dao的函数并返回dao的返回值。我应该这样做:
class MyRepo(...): FooDao by fooDao, BarDao by barDao { //fun doSomethingWithFoo no longer necessary //fun doSomethingWithBar no longer necessary }
但是,Android Studio却让我措手不及 Type parameter T of BaseDao has inconsistent values: FooEntity, BarEntity
这是否意味着减少所有这些样板就失去了希望MyRepo.doSomethingWithFoo = fooDao.doSomethignWithFoo
?还是有办法做到这一点?
我试图在MyRepo中实际上重写BaseDao函数,以为它将停止抱怨FooEntity和BarEntity:
class MyRepo(...): BaseDao, SetDao by setDao, ... { override fun insert(t: Any): LOng= 0L }
但这只会在不一致的类型消息中添加“任何”。