Noticed something while writing some unit tests: `...
# announcements
j
Noticed something while writing some unit tests:
Copy code
class Foo

class Bar(
    private val foo: Foo
) {

    override fun equals(other: Any?): Boolean {
        if(other !is Bar) return false
        return this.foo == other.foo // it works?
    }

    override fun hashCode(): Int {
        return foo.hashCode()
    }
}

fun test() {
    val foo = Foo()
    val bar = Bar(foo)
    val test = bar.foo // private, cannot access
}
Could not find any documentation on this behavior. I mean, seemed convenient but it just felt... weird that it worked on the equals override 🙂
c
Do you mean accessing the private variable on the Bar parameter inside of the overrided fun equals? Now I see. I does seems funny but truly convenient
m
All other OOP languages I can think of also allow that. `private`means more of local to the type, not local to the instance.
j
hmmm ok, I guess I don’t get to override equals much these days 😅 still, I wonder how the compiler does that... is it specific to equals?
m
Nope, inside type
Foo
you can access private members of any object of type `Foo`which just happens to be most used with the `this`parameter. You may even access these in companion objects, other objects, nested classes etc as long as they are inside the `Foo`class.
E.g.:
Copy code
class Foo {
    private var bar = 1
    
    companion object {
        fun baz(foo: Foo) {
            foo.bar++
        }
    }
}
j
oh ok, make sense 🙂 thanks for the explanation 🙂
l
If you are referring to the equals behaviour, Kotlin's double equals just calls the .equals(other) method. You need === to match Java's reference-equality behaviour. This takes a while to get used to.