null - Java Map w @NonNull Value Type and @Nullable get() method result? -
i have method returning custom map implementation, entries consist entirely of non-null keys , values, add type annotations in order indicate clients may iterate on map.entry's without having check them null values: map<@nonnull string,@nonnull string>
the problem map.get method api specifies null returned attempt retrieve value key isn't present in map, , annotating method implementation return @nullable string generates compiler warning return type incompatible @nonnull return specified map.
i understand map.get api created today might perhaps return java.util.optional result or throw nosuchelementexception, but, being beholden existing collections api, possible remain compliant method specification , specify map contains @nonnull values?
much thanks.
unfortunately, map api not compatible null annotations. map.get returns generic type v, when define v @nonnull, violates api since null must allowable return value.
this known limitation of null annotations, , resolved when nullity profiles libraries implemented. until then, workarounds check map.containskey before getting value instead of checking value afterwards null, or avoid using @nonnull on map value types.
Comments
Post a Comment