需要泛型 找到字符串 kotlin.String

Generics required String found kotlin.String

class CacheEntry<T>(val value: T, val size: Long)

interface Cache<T>{
    val NO_ENTRY_FOUND : CacheEntry<T>
}

class CacheImpl<String> : Cache<String>{
    override val NO_ENTRY_FOUND =  CacheEntry<String>(value = "not_found", size = -1)
}

我收到这个错误:

Error:(12, 65) Gradle: Type mismatch: inferred type is kotlin.String but String was expected

我不明白为什么这不起作用。

在您的例子中,String 是类型参数的名称,而不是标准的 String 类型,因此问题中的代码等同于:

class CacheImpl<T> : Cache<T> {
    override val NO_ENTRY_FOUND = CacheEntry<T>(value = "not_found", size = -1)
}

CacheEntry 需要 T 作为第一个参数,但您提供了 String,这就是您看到编译错误的原因。修复非常简单,您只需从 CacheImpl 声明中删除 String

class CacheImpl : Cache<String> {
    override val NO_ENTRY_FOUND = CacheEntry<String>(value = "not_found", size = -1)
}