why is `x.Y` not allowed ?
# announcements
l
why is
x.Y
not allowed ?
blob thinking upside down 1
🤔 2
b
Can be achieved with this val Y = object: {}
Although I admit, I'd expect this to work too.
a
Not sure what you mean, looks like working: https://pl.kotl.in/FLNhgaKuQ
h
In JVM, objects are compiled as classes with a private constructor and a static INSTANCE field. If you access an object inside an object using an instance, you call X.INSTANCE.Y.INSTANCE, but you should X.Y.INSTANCE (and calling static methods on an instance is a code smell) . As
x
is
X.INSTANCE
, it could have some kind of a mutable state, but with
X.Y
it is clear,
Y
is not affected by any changes from
x
.
Copy code
object X {

    var s = 42

    object Y {
        var l = s
    }
}

fun foo() {
    println(X.Y.l)
    val x = X
    println(X.Y.l)
    x.s = 1
    println(X.Y.l)
}
foo()
n
@Arkadii Ivanov: your example is not not addressing the question. Try https://pl.kotl.in/9_AvaZ9w4 for yourself. For the record: I also would have expected that this works.
a
That is because of the poor Slack UX, I got the question wrong. Sorry.