【问题标题】:When returning Generic type * I get error not enough information to infer type variable T当返回通用类型 * 我得到错误没有足够的信息来推断类型变量 T
【发布时间】:2021-02-23 07:05:15
【问题描述】:

我有以下代码-


// My function - 
suspend fun leaveGroup(isSoloGroup: Boolean, groupMemberEntity: GroupMemberEntity): Resource<*> {

        val snapShot = remoteDataSource.getSnapshot(GROUP_MEMBERS_COLLECTION) {
            whereEqualTo(Constants.DatabaseProperties.ID, groupMemberEntity.id)
        }

        if (snapShot is Resource.Exception) {
            return snapShot
        }

        val delete = remoteDataSource.deleteSnapshot(snapShot.data!!)
        if (delete is Resource.Exception) {
            return delete
        }

        if (isSoloGroup.not()) {
            return (Resource.Success()) // This is where the error occurs 
        }
        // Code continues ...
    }


//My resource class - 

sealed class Resource<T> {

    abstract val data: T?

    data class Success<T>(override val data: T? = null) : Resource<T>()

    data class Exception<T>(val throwable: Throwable, override val data: T? = null) : Resource<T>()

    data class Loading<T>(val hasStarted: Boolean = false, override val data: T? = null) : Resource<T>()

}

由于某种原因,当我返回类型 Resource&lt;*&gt; 时,类 Resource. Success 不能用其默认值 null 进行实例化,我必须明确地给它一个空值 - 否则我会收到错误消息 Not enough information to infer type variable T。在构造函数中给它 null 显然是有效的,但这不是干净的代码,并且使默认值变得多余。我错过了什么?

【问题讨论】:

  • return Resource.Success&lt;Nothing&gt;()

标签: android oop kotlin


【解决方案1】:

类型系统中有Nothing类型,没有值,无法实例化。

因为 Nothing 没有值,Nothing? 实际上是 Kotlin 中只捕获 null 值的类型。

也就是说,当你声明这样的东西时:

val someVariable = null

someVariable 的推断类型是Nothing?

所以如果你想存储空值,你必须给它一个类型(编译器不能直接推断它,因为它可以是String?Int?等),所以给它明确的Nothing?比较合适。

if (isSoloGroup.not()) {
    return Resource.Success<Nothing>()
}

【讨论】:

  • 很好的解释。从你所说的理解,换句话说,我试图做的是从可能的类似 JavaScript 的 Undefined 中获取一个空值,这是不可能的,因此发生了错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 2021-02-11
相关资源
最近更新 更多