Kotlin接口中的Carat语法

4

或许可以稍微解释一下。

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

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

还有一个名为“Book”的接口:

interface Book {
    fun write(page: Page)
    fun read(title: String) Page
}

我的问题是如何使用插入符号泛型语法来指定这些方法必须由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
    }
}

我对泛型的工作方式理解错了吗?非常感谢任何帮助。

2个回答

4

我对泛型的理解有误吗?

是的,您有一点误解。

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
}

1
谢谢,这正是我想做的。只是在文档中无法确定。通用约束!谁能想到!再次感谢! - Patty P

2

您可以使用 Kotlin 约束,特别是上限约束:

interface Book<T : Page> {
    fun write(page: T)
    fun read(title: String) : T
}

docs here


如果链接失效,您可能需要引用或总结相关部分。 - Ruckus T-Boom
@RuckusT-Boom 我不知道怎么做,我看到其他用户已经做了。 - developer_hatch
请将以下与编程有关的内容从英语翻译成中文。仅返回已翻译的文本:只需复制/粘贴(可能要重写)您在答案中引用的页面的相关部分。 - Ruckus T-Boom
1
@RuckusT-Boom 谢谢!我找到了!我已经编辑了答案并加上了正确的链接。 - developer_hatch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接