https://kotlinlang.org logo
Title
b

bod

03/11/2018, 4:10 PM
Hello, World! Hey, when doing sealed classes, the compiler complains that the types can only be subtypes of the sealed class. Does that mean that the one example on the official doc is wrong?
d

diesieben07

03/11/2018, 4:18 PM
Can you show your code?
b

bod

03/11/2018, 4:26 PM
data class Pagination(val pageIndex: PageIndex, val itemCount: Int = DEFAULT_ITEM_COUNT) {
    companion object {
        const val DEFAULT_ITEM_COUNT = 25
    }


    sealed class PageIndex {
        internal abstract val before: String?
        internal abstract val after: String?

    }

    object FirstPage : PageIndex() {
        override val before: String? = null
        override val after: String? = null
    }

    data class Before(private val elementId: String) : PageIndex() {
        override val before = elementId
        override val after: String? = null
    }

    data class After(private val elementId: String) : PageIndex() {
        override val before: String? = null
        override val after = elementId
    }
}
And the error is “This type is sealed so it can be inherited by only its own nested classes or objects”
d

diesieben07

03/11/2018, 4:28 PM
You can only inherit from a sealed class with either a class nested inside the sealed class or a class in the same file of a top level sealed class. Your
PageIndex
is not top level, so only classes nested inside
PageIndex
can inherit from it.
b

bod

03/11/2018, 4:29 PM
Oh. So strange 🙂 OK so if I move everything outside of
Pagination
it should work
d

diesieben07

03/11/2018, 4:29 PM
Yes. Seems weird but that's how it is...
b

bod

03/11/2018, 4:30 PM
it does work indeed! I wonder why this restriction exists. Anyway, many thanks 🙂