generics - Kotlin 接口(interface)中的 Carat 语法

标签 generics kotlin

可能有助于解释这一点。

假设我有一个名为 Page 的抽象类,它看起来像这样:

abstract class Page {
    abstract fun title() : String
}

还有一个叫做 Book 的接口(interface):
interface Book {
    fun write(page: Page)
    fun read(title: String) Page
}

我的问题是如何使用 carat 通用语法来指定方法必须由 Page 类的派生实例使用。也许是这样的:
interface Book<Page> {
    fun write(page: Page)
    fun read(title: String) : Page
}

class AdventureBookPage(val pageTitle: String, val content: String) : Page() {

    override fun title() : String {
        return title
    }
}

class AdventureBook : Book<AdventureBookPage> {
    override fun write(abp: AdventureBookPage) {
        // do writing ops
    }
    override fun read(title: String) : AdventureBookPage {
        // do read ops
    }
}

我是否误解了泛型在这里的工作方式?任何帮助将不胜感激。

最佳答案

Am I misunderstanding how generics work here?



对,一点儿。
interface Book<Page> {
    fun write(page: Page)
    fun read(title: String) : Page
}

您在这里基本上声明的是:
interface Book<Foo> {
    fun write(page: Foo)
    fun read(title: String) : Foo
}
Page只是一个标识符,代表任何旧类型。你可以做一个Book<String> , 一个 Book<HttpClient>Book<ArrayList<String>> .通常,而不是 FooPage , 标识符 T被使用,代表“类型”。

标识符与您自己创建的类型相匹配的事实只是偶然的。

我想你试图声明的是一本书是页面的集合,或者比页面更专业的任何东西。这称为 'generic constraint' ,你会这样表达:
interface Book<T : Page> {
    fun write(page: T)
    fun read(title: String) : T
}

关于generics - Kotlin 接口(interface)中的 Carat 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47164320/

相关文章:

kotlin - 将 null 值传递给具有不可为 null 的默认参数的 Kotlin 方法

java - 无法为类型为 org.gradle.api.publication.maven.internal.deployer.DefaultGroovyMavenDeployer 的对象获取未知属性 'GROUP'

kotlin - 我应该使用哪些序列化依赖项?

c# - System.Runtime.Caching.MemoryCache 的通用实现

java - Max element - Sun 的答案 VS 我的

java - 如何通过类类型委托(delegate)构造函数的实例化?

c# - C# 中更复杂的扩展泛型

java - 泛型和静态方法

android - 使用 pytorch android API 检测图像是否模糊

Kotlin日期时间格式异常