Reputation: 19
I'm currently teaching myself Kotlin and am a bit confused at how visibility is working.
class Test(val name: String) {
private fun sayName() {
println(name)
}
fun askName(test: Test) {
test.sayName()
}
}
val test1 = Test("one")
val test2 = Test("two")
test1.askName(test2)
The result is "two". Why am I able to access the private method of another instance? Shouldn't the sayName() method only be accessible from within its own instance?
Upvotes: 0
Views: 765
Reputation: 18577
I think you're describing path-dependent types; see this question.
Kotlin doesn't have those, as IllidanS4 says: its access control looks only at classes, and not instances.
(Scala has them, but I'm not aware of any other mainstream languages that do. (I'm sure people will let me know if there are!) I'll leave you to decide whether that implies anything about how widely they're needed…)
Upvotes: 0
Reputation: 13197
Visibility in Kotlin works the same way like in many modern programming languages (including Java) - it affects which types can see the given members, not which instances. sayName
is visible only in the actual class where it is defined, but the compiler doesn't have to check whether the test
parameter is the current instance or another one; it would have to be pointless since you as the creator of the class know perfectly well when it is accessed and use and you can make that restriction yourself if you wish.
There could be some exceptions to this regarding subtyping in some languages, but this is the gist of it.
Upvotes: 2