is it possible to define a member to look like it ...
# announcements
b
is it possible to define a member to look like it is hidden within another? that is, could i define a class like:
Copy code
class Foo {
  var baz: Int
}
such that callers accessed
baz
by doing
Foo.bar.baz
?
s
Not sure why you’d want this, but this would work:
Copy code
class Foo {
  var baz: Int
}

val Foo.bar get() = this
Now, you can call
val value: Int = myFoo.bar.baz
b
ah that's pretty slick! don't suppose there'd be a way to do it which would make
baz
only accessible through
bar
?
the use case is that i've got some properties in Foo that logically would be nested into an inner member, but Foo needs to potentially take action when they're modified (and access Foo data), so was thinking about this as a possible method
and an inner class doesn't feel like the right model, conceptually
s
Then an inner class would be good for this. Why don’t you think it’s right to use an inner class?
b
it feels like this class should be more 'independent' than existing as an inner class, but maybe i'll rethink that.
s
Copy code
interface IFoo {
    var baz : Int
}

class Foo {
    private var baz: Int = 8

    val bar : IFoo = object : IFoo {
        override var baz: Int
            get() = this@Foo.baz
            set(value) { this@Foo.baz = value }
    }
}

fun main() {
    Foo().bar.baz
}
1
b
ah that's i think what i was looking for. thanks! i'll weigh that vs the inner class
s
Or weirder 🙂
Copy code
interface InnerFoo {
    val bar : Foo
}

class Foo private constructor() {
    companion object {
        operator fun invoke() : InnerFoo = object : InnerFoo {
            override val bar = Foo()
        }
    }

    private var hiddenProp: Int = 0

    var baz : Int = 0
}

fun main() {
    val foo = Foo()
    foo.bar.baz
    foo.bar.baz = 29
}
😮 1