I've added a generic method to an interface, so that every class which implements that interface has a fluent method to set a parameter on that class, but I'm getting "Unchecked cast" warning on the return statement, so I'm suppressing it.
Since I'm uncomfortable with just suppressing the warning, and casts have always felt like code smells since I came to java from C#, where they most definitely are, I wonder under what circumstances that warning might apply. Alternatively, I wonder if there is a more type safe way of implementing what I want.
Wanting to be able to use
var model = new MyModel().withBoundsToFit(true);
rather than
var model = new MyModel();
model.setBoundsToFit(true);
I created this method in IBoundsToFit:
//@SuppressWarnings("unchecked")
default <T extends IBoundsToFit> T withBoundsToFit(boolean boundsToFit) {
setBoundsToFit(boundsToFit);
return (T) this; // Type safety: Unchecked cast from IboundsToFit to T
}
What I don't understand is how, when I'm already constraining T
to classes which extend IBoundsToFit
, in what situation it could be unsafe to do this cast.