2 ms·
Two things: 1. Many other languages let you redefine field assignment syntax to be a function call, which is basically what a 'property' is in Kotlin. Java doe
by thu2111 7y ago
Two things:
1. Many other languages let you redefine field assignment syntax to be a function call, which is basically what a 'property' is in Kotlin. Java doesn't.
2. The Java ecosystem distributes software in binary bytecode form and cares about binary/API compatibility.
The combination of these two mean that even if you don't want to run any code on field assignment today, if there's any chance you might want it tomorrow you have to plan for it now by using functions instead of naked fields. Changing the latter to the former means updating all the use sites.
The big win of language integrated properties is you can go from (in Kotlin):
class Thing(val veryLongText: String)
to
class Thing(text: String) {
val veryLongText by lazy { text.toLowerCase() }
}
without any of the places that use Thing.veryLongText noticing the difference. The first code just stores the string as an ordinary field. In the second, we've decided the text should actually be lower case and that lower-casing should be done on demand then memoized for efficiency.
In Java, if you want to do that, you'd have needed to write a getVeryLongText() method from the start, as otherwise you'd have nowhere to add the extra code.