At the moment, I type in type annotations for public val
s, var
s and def
s in my Scala classes, traits and objects[1] - either by inferring the types of them mentally, or occasionally by hovering over the identifier in Eclipse to find out what the presentation compiler thinks the type should be[2]. How can I conveniently add these type annotations automatically?
The purpose of adding in explicit types is to "lock in" the type of a public member of a template, so that if a developer changes the definition of the member in future in a way that results in an incompatible type, they will get a compile-time error unless they deliberately change the type annotation as well.
Footnotes:
[1] except if they override a member in a supertype and the type should be the same as the type of the overridden member, which is usually the case for overrides in my code.
[2] This isn't always correct; the presentation compiler seems to be weak when it comes to members that override members in supertypes.
This has been implemented in the Scala IDE in Kepler Eclipse 4.3 update.
Use ctrl/cmd-1 on the identifier and choose "Add explicit type ...".
See here.
For those who use IDEA on Mac, the following works:
⌥ (Alt) + return
That is, press and hold Alt and hit return/enter.
Then select "Add type annotation to value definition".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With