Reputation: 2404
I can't figure out the proper way to have a default constructor argument that is an Guava Optional. The following code will not compile with Java 1.6
public class ShoppingCart implements Serializable {
private final Optional<DiscountCoupon> discountCoupon;
public ShoppingCart() {
this(Optional.absent());
}
public ShoppingCart(Optional<DiscountCoupon> dc) {
Preconditions.checkNotNull(dc);
if (dc.isPresent()) {
Preconditions.checkArgument(dc.get().getPennyDiscount() != 0 ||
dc.get().getPercentDiscount() != 0);
}
discountCoupon = dc;
}
Error reported is is:
/Users/pfarrell/sandbox//com/wayfinderdigital/struct/ShoppingCart.java:29: cannot find symbol
symbol : constructor ShoppingCart(com.google.common.base.Optional<java.lang.Object>)
location: class com.wayfinderdigital.struct.ShoppingCart
this(Optional.absent());
Upvotes: 1
Views: 1364
Reputation: 120546
Try changing
this(Optional.absent());
to
this(Optional.<DiscountCoupon>absent());
The second uses an explicit type parameter specification, so doesn't require type parameter inference. Type parameter inference can be done based on input parameters or based on the type to which an expression is being assigned, but many other site-of-use inferences don't work automatically so the type parameter assumes its lower bound.
Upvotes: 3
Reputation: 198321
Java can't automatically infer the generics from the code you've written. Instead, use
public ShoppingCart() {
this(Optional.<DiscountCoupon>absent());
}
(Though I have to ask -- are you sure that Optional
is really appropriate here?)
Upvotes: 5