Kotlin继承

时间:2017-05-17 01:57:15

标签: generics inheritance kotlin

我目前正在学习将凌乱的代码拆分为DDD(注释,学习)范例。实体(IEntityIUser)是域层,由接口组成,然后在数据层(BaseEntityUser)实现。通过存储库模式访问数据。但正如我为IUserRepository定义的那样,要返回IUser,在数据层我必须手动将其User投回IUser以匹配返回签名。

如何避免施法?谢谢。

域层

interface IEntity
{
    var id: Long?
    var name: String?
}

interface IUser : IEntity
{
}

interface IBaseRepository<T: IUser>
{
    fun get(id: Long): Observable<T?>
}

interface IUserRepository : IBaseRepository<IUser>
{
}

数据层

abstract class BaseEntity() : IEntity
{
    @SerializedName("id")
    override var id: Long? = null

    @SerializedName("full_name")
    override var name: String? = null
}

class User() : BaseEntity(), IUser
{
}

interface UserRetrofitApi
{
    @GET("user/{uuid}/")
    fun get(id: Long): Observable<User?>
}

class UserRepository(private val _api: UserRetrofitApi) : IUserRepository
{
    override fun get(id: Long): Observable<IUser?> {
        return _api.get(id) as Observable<IUser?> // How to avoid casting here without resorting to generic UserRepository<T: IUser>
    }
}

2 个答案:

答案 0 :(得分:1)

在基本存储库中声明您的get函数,如下所示:

fun get(id: Long): Observable<out T?>

同样将get中的UserRepository功能更改为:

override fun get(id: Long): Observable<out IUser?> {
    return _api.get(id)
}

有关详细信息,请参阅the docs on variance

答案 1 :(得分:0)

如果我理解正确,您只需更改即可将UserRetroFitApi.get的结果返回Observable<IUser?>

class UserRetrofitApi
{
    fun get(id: Long): Observable<IUser?> {
        val user = User()
        user.id = 1
        user.name = "User 1"
        return Observable.just(user)
    }
}