Carat Syntax in Kotlin Interfaces

Help explain this a bit.

Say I have an abstract class called "Page" that looks like this:

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

And an interface called Book:

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

My question is how can I use the carat generic syntax to indicate that methods should be used by a derived instance of the Page class. Maybe like this:

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
    }
}

I do not understand how generics work here? Any help would be greatly appreciated.

+4
source share
2 answers

I don’t understand how generics work here?

Yes a little.

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

What you basically stated here:

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

Page , . Book<String>, a Book<HttpClient> Book<ArrayList<String>>. , Foo Page, T, "".

, , , .

, , - , . 'generic constraint', :

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

kotlin, :

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

docs

+2

Source: https://habr.com/ru/post/1688899/


All Articles