Is it possible to access an extension property giv...
# getting-started
j
Is it possible to access an extension property given this setup?
Copy code
fun main() {
    val book = Book("Kotlin Basics", List(10) { Page(it + 1) })
    
    val p = book.pages[4] // get the fullName from this scope given `book` and `p`?
}


class Book(val name: String, val pages: List<Page>) {
    val Page.fullName: String
        get() = "$name: Page $number of ${pages.size}"
}

class Page(val number: Int)
y
Yes, simply do:
Copy code
fun main() = with(Book("Kotlin Basics", List(10) { Page(it + 1) })) {
    val p = pages[4]
    println(p.fullName)
}


class Book(val name: String, val pages: List<Page>) {
    val Page.fullName: String
        get() = "$name: Page $number of ${pages.size}"
}

class Page(val number: Int)
This also works with context parameters!
j
Don't know why I didn't think of that, thanks!
k
But do you really want to define it like this? The
Page.fullname
getter function has an implicit parameter (a receiver) that references the
Book
but you're not using it. If you don't need such a receiver, consider defining
fullname
outside of
Book
or in a companion object.
y
@Klitos Kyriacou It is being used!
name
and
pages
both come from
Book
.
🤦‍♂️ 1
k
Indeed they do, sorry for the noise.