I’m playing around with Kotlin and I recently ran into a strange scenario with extensions. I’m having a hard time understanding why extensions, that are declared inside a class, are unavailable directly unless a with
is used. For example:
fun main(args: Array<String>) {
val john = Person()
println(john.state.isSingle) // Unresolved reference: isSingle
println(with(john) { state.isSingle }) // Will need to use this instead
}
class Person(val state: State = State.SINGLE) {
val State.isSingle: Boolean
get() {
return this == State.SINGLE
}
enum class State {
SINGLE, MARRIED
}
}
Furthermore, when an extension is declared as a top level property, direct access to the extension is now possible, i.e:
fun main(args: Array<String>) {
val john = Person()
println(john.state.isSingle) // Works
}
class Person(val state: State = State.SINGLE) {
enum class State {
SINGLE, MARRIED
}
}
val Person.State.isSingle: Boolean
get() {
return this == Person.State.SINGLE
}
What are the differences between declaring it as top level vs inside another class that makes direct access impossible? If declared inside a class, wouldn’t the extension have access to the instance its inside?