Dag 1 ”Seven roads to hell” rullar igång i högtalarna och jag går ut på scenen. Natten är lugn, och det är bara fåtal kunder i...
More on Constructors
Here’s some more you could do with implicit constructors. Remember this class?
1 2 3 4 5 6 | class Greeter(String name = "stranger") { function greet() returns Void { echo("Hello #{$name}!"); } } |
It turns out that the constructor argument “name” live on within the scope of the class. That’s interesting, because one of the main pains in Java is beans, and bean accessors. We’ve already seen that we can alleviate that with field access. But how about making it even simpler. Have a look at the following, mutable and completely awesome bean:
1 2 | @Mutable class Person(@Field String firstName, @Field String lastName) { } |
Adding the “@Field” annotation generates automatic fields, including getters for the argument, and since he class is mutable, it also generates setters. The above would be equivalent to the following Java bean:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class Person { private String firstName; private String lastname; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } |
The amount of crud reduced is ridiculous. There is of course the problem that if you mix “@Field” annotations with ordinary arguments and an explicit constructor it might get too messy. But hey, it’s a neat idea.