3 ms·
While I don't agree with the general tone of the above comment, I am curious if anyone can enlighten me on why one would need a getter on a member that's alread
by saghm 9y ago
While I don't agree with the general tone of the above comment, I am curious if anyone can enlighten me on why one would need a getter on a member that's already public.
- gregghz 9y agoyou don't. Scala produces them automatically for case classes. Kotlin will treat x.count as x.getCount() if getCount exists and count doesn't. They are mostly a side effect of the tools and not strictly required. Especially in Kotlin and Scala where data tends to be immutable by default there isn't much to gain by using getters. If your "getter" is doing more than getting the value then maybe you should not call it a getter (imo).
- saghm 9y ago> If your "getter" is doing more than getting the value then maybe you should not call it a getter (imo) I'd definitely agree there! In fact, I might go further and say that if your "getter" does more than just return a member, then by definition it isn't a getter
- lgas 9y agoI think the heart of the question was more, if the members are already public, why does Scala need to produce getters for them, why not access the members directly?
- gregghz 9y agoI honestly don't know.
- curun1r 9y agoI forget who said it, but there's a quote along the lines of, "There's no problem in programming that can't be solved by adding another layer of indirection. Getters are just that, a layer of indirection. So they give you a hook to intercept a call and do something that wouldn't be possible with direct field access. Perhaps you want to lazy-load the field, or dynamically compute its value under certain circumstances. Whatever it is, if you use getters from the outset, you won't have to change code that calls the getters when you decide you need that indirection.
- saghm 9y agoFair enough, although those types of things seem like they'd need to be explicitly written, not auto-generated by a compiler (like the ones described as existing for Scala)
- simon_o 9y agoThat's the whole point of what Scala is doing. Allow flexibility to support such requirements later on, without forcing people to break source and binary compatibility, unlike in Java, C# etc. That's the reason why you can e. g. implement or override a def with a val.