可能有助于解释这一点。
假设我有一个名为 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>>
.通常,而不是 Foo
或 Page
, 标识符 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/