Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert inferred type annotation for Scala val/var/def

At the moment, I type in type annotations for public vals, vars and defs 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.

like image 245
Robin Green Avatar asked Mar 25 '23 03:03

Robin Green


2 Answers

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.

like image 172
Traveler Avatar answered Mar 26 '23 16:03

Traveler


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".

like image 26
bjfletcher Avatar answered Mar 26 '23 18:03

bjfletcher