Repository navigation
Description
In the draft proposal, there's a part that allows for overrides to have value parameters with contravariant nullability:
The method’s parameter types may have wider nullability than the corresponding superparameters' types, meaning, it suffices for superparameters to be type-convertible to the overriding method’s parameter types (while base types have to follow the normal rules of the compiler so overriding works as expected).
That might be a problem for the Kotlin compiler since in pure Kotlin value parameters are not contravariant in overrides and we apply the same logic when looking at the annotated Java code.
The reason we don't allow contravariant parameters in override is basically the same as in Java: they might be considered as overloads. In Java, one can not override with a wider-typed parameter (types should be equal). The same applies for Kotlin, but we have nullability as a built-in part of the type system.
interface A {
fun foo(x: String)
}
class B : A {
override fun foo(x: String) {
}
@JvmName("fooNullable")
fun foo(x: String?) {} // is a different overload for `foo`
}
fun main() {
B().foo("") // resolved to the not-nullable
B().foo(null) // resolved to nullable
}
That means that when we see contravariant nullability in Java annotations, such code is assumed to be illegal thus we ignore annotations info for such parts completely as inconsistent:
interface A {
void foo(@NotNull String x);
}
class B implements A {
@Override
public void foo(@Nullable String x) {
}
}
B::foo has signature like fun foo(x: String!), i.e. it has unknown nullability from Kotlin point-of-view.
But at the same time it's fine transforming from unknown nullness to both NotNull and Nullable:
interface A {
void foo(String x, String y);
}
class B implements A {
@Override
public void foo(@Nullable String x, @NotNull String y) {
}
}
In the above example B::foo is perceived by Kotlin as fun foo(x: String?, y: String)
Activity
donnerpeter commentedon Jul 23, 2019
In Java, IntelliJ IDEA's inspections currently allow nullable parameters overriding notnull ones, as there were such requests from users.
kevin1e100 commentedon Jul 23, 2019
As mentioned before I think we can just leave out parameter type contravariance for now to unblock prototyping, as from the Java point of view we should be able to safely add it later (please correct me if I'm missing something).
I'll just point out that the overload-vs-override concern seems possibly solvable to me, since Kotlin uses different JVM method names in that case. That technically would be consistent with a proposal that allows contravariant nullability specifiers for methods that override each other according to the JVM, though it probably couldn't be allowed in a Kotlin class overriding another Kotlin class.
The fact that kotlinc infers platform types when it sees contravariant overrides is certainly problematic but maybe could be avoided as well? Again I'm happy to defer this, but I do expect users to ask for contravariance eventually (see @donnerpeter comment above), so maybe worth thinking about if it could somehow be accommodated in kotlinc.
kevin1e100 commentedon Jul 23, 2019
For posterity, here's some (about-to-be-deleted) rationale that was in the proposal for why contravariant parameter types might be interesting:
cpovirk commentedon Jul 24, 2019
One distinction that is already made in the doc but I want to call out here is that we still plan to accommodate overriding methods whose parameters types include unknown nullability. That solves part of the problem here. (And it solves that part of the problem better than mere contravariance, since it applies also to conversions between
List<@NullnessUnknown String>andList<@NotNull String>, which are unrelated types and thus would not be covered by contravariance support.) I'm hoping that it solves a lot of the problem. And I'm hoping that another part of the problem is methods whose parameters types are traditionally annotated as non-null because people are using annotations/tools that don't support annotating type parameter bounds but should instead have parametric nullability. Once parametric nullability is widely supported, users might see less need for contravariant parameter types. And, as noted earlier, contravariance doesn't help with cases likeList<@NullnessUnknown String>andList<@NotNull String>, anyway.I still can imagine that we'd want to support this someday, but +1 for putting it off for now. And when we do allow it, I think it's worth considering whether it's worthy of a warning, since it might happen accidentally (or intentionally but in cases in which there's a better solution available) as much as it happens in "good" cases.
kevinb9n commentedon Jul 24, 2019
I am also more than happy to jettison parameter contravariance for the time being.
cpovirk commentedon Sep 23, 2019
If we really wanted, we could annotate
Collection.containsand similar methods as requiring[@NotNull] Object, since some collections do throw when called withcontains(null). Then we'd want for subclasses to be able to override those to accept@Nullable Object. However:ArrayList.contains(@Nullable Object)and live with the occasionalNullPointerException. (This appears to be what the Checker Framework does -- though then it definesTreeSetwithcontains(Object). I'm a little surprised that that is allowed (probably it isn't, except in stubs?). But it is safer for people who have a reference of typeTreeSet, albeit only by being even more conservative than ideal.) Or at most we'd use@NullUnspecified, which might permit subclasses to change nullability in overrides in even more flexible ways.cpovirk commentedon Oct 11, 2019
It sounds like we can probably close this, at least as a way of saying "not yet?" (Or maybe we want some other way of marking issues as "post-1.0?")
(As for my post just above this one, it seems pretty clear that kevinb9n, at least, is in favor of
contains(@Nullable Object), too, based on this and this.)mernst commentedon May 28, 2020
Formal parameter type contravariance is consistent with Java, so it is natural and strongly desirable. If we were designing Kspecify rather than Jspecify, we might make a different decision.
I think we should accommodate Kotlin whenever we can, but we should never degrade the behavior of Jspecify on Java code in order to conform to Kotlin's different semantics.
kevinb9n commentedon May 28, 2020
I've kept coming back to this in my mind, and am just gonna reopen it for now. It may not be a critical priority right now, but I don't think that's what the open/close status is supposed to show.
If we don't have parameter contravariance, doesn't that mean that a method and all of its overrides can only have their annotations changed in perfect lockstep? That's against a project requirement, and it just feels bad to prohibit a method from accepting null if it wants to unless it changes the whole world around it.
cpovirk commentedon May 29, 2020
(Reopening sounds fine.)
RE: changing annotations in lockstep: No, that's not required. See #49 (comment). Note also that, even with specified nullness, library authors are likely to have the option to suppress the error on the overriding method. (But I grant that it's unfortunate to have to suppress in the case of a contravariant override (which is safe) just as you do for a covariant override (which is not).)
RE: consistency with Java: I can see how contravariance is:
The one way in which it's arguably inconsistent is that Java doesn't support such contravariance at present. For example, I can't override
foo(String)withfoo(Object): I just get an overload.Now, again, overloading isn't possible in our case (since
foo(String)andfoo(@Nullable String)have the same erasure), so I'm not saying that users should be able to define two separate methods with those signatures. I just mean that, if users are able to override one with the other, we'd be somewhat breaking new ground.I think we're all in agreement on this, but I wanted to make sure I'm not missing a deeper point that you're making.
Furthermore, breaking new ground might be perfectly fine. (I don't think I've formed a strong opinion yet. My main opinion so far is "not yet" :))
kevinb9n commentedon Jun 4, 2020
re: "lockstep", right, I forgot that we were going to have to special-case unspecified. It would just be nicer to have the right thing happen for unspecified as a simple consequence of our general contravariant-parameters and covariant-returns support.
kevinb9n commentedon Jun 4, 2020
BTW, in the case of covariant returns I don't think jspecify even needs to do anything; just by explaining how the annotations are meant to modify types, users "should" assume they can do covariant returns because that's just how return types work.
This one would need to be called out somehow though, because existing knowledge of types makes the wrong implication.
cpovirk commentedon Jun 12, 2020
Even with contravariant parameter types, we'd still like for unspecified to be considered to be "the same type" as both nullable and non-null.
The reason is parameterized types: Suppose a method in an unannotated interface accepts a type like
@Unspec List<@Unspec String>. If we want to implement that in an annotated class, we would like to avoid@Unspec. Even if the right type is@Nullable List<@Nullable String>, that's not a supertype of the old method's parameters because parameterized types are invariant. So contravariance isn't enough.But you have made me see that, just as the "same type" check can permit things that contravariant parameter types cannot, the reverse is also true: Contravariant parameter types can permit some declarations to work without warnings or errors, like if I override a method that accepts
@Unspec Objectwith one that accepts@Nullable Object.Still, I see "the same type" as the essential feature and contravariant parameter types as the possible add-on.
41 remaining items
netdpb commentedon Apr 9, 2024
Current decision: When a parameter type is a supertype of the parameter type it overrides (a "contravariant parameter"), there is no resulting "JSpecify-based" finding. (A tool can report something if it wants to, but that is separate and should not be enabled when running JSpecify tests.)
Argument for changing: Kotlin does not allow such overrides. However, JSpecify focuses on Java declarations.
Timing: This must be decided before version 1.0 of the spec.
Proposal for 1.0: Finalize the current decision. If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.
cpovirk commentedon Apr 11, 2024
I keep feeling that I'm almost on top of this issue, only for things to get slippery again.
JSpecify currently says essentially nothing about when its subtyping check and similar checks should be deployed on Java source. This issue might be about starting to say such things, or it might be about what conformance tests we write.
Part of my concern has been that we both seem to want to say "We don't tell checkers when to apply or not apply our checks" and also seem to want to say "But by writing a conformance test about this situation, we are implicitly telling checkers that applying our checks here would be in some way 'unjustified.'"
The samples tried to dodge this question by saying that they're written under the assumption of JLS-like rules (which of course ban contravariant parameters) but that that those rules (a) have no necessary connection to what checkers do and (b) are more strict than "necessary":
[edit: The spec says something similar.]
I would like more clarity on whether this issue is "We will not write a conformance test for this case" or "We will write a conformance test for this case that contains no cannot-convert comment (or override-conflict comment or whatever)" or "We will recommend that tools not produce errors in such situations" or some combination of those or what.
I also wonder a little if we're opening a can of worms by trying to go beyond the JLS rules for when to apply checks. For example, if a supermethod has a type parameter
<T extends Object>, is it OK for a submethod to declare it as<T extends @Nullable Object>if the resulting changes produce only covariant return-type changes and contravariant parameter-type changes? Maybe we don't need to care about that relative edge case. I just think I recall some complexity in the Checker Framework that seemed to arise from trying to handle such overrides. [edit: It came up not long after I wrote this :)] So I'd also like to have some idea of whether we want to say something like "We've thought specifically about contravariant parameter types, and we think they work well in practice" or "We think that going beyond the JLS is safe in general."I may be making a big thing out of an inconsequential decision. Part of my concern is that it keeps sounding inconsequential, only for phrasing about what is (e.g.) "correct" to crop back up.
If I had managed to collect my thoughts earlier, I would have talked to kevinb9n about this (more) in person.... We should probably talk sometime.
cpovirk commentedon Apr 12, 2024
tl;dr I think that "finding" and "JSpecify-based" are undefined terms that are making the question slippery.
My proposal would be:
If it helps, I would also be open to agreeing to expand some non-normative resources to explain why contravariant parameters are worth considering.
cpovirk commentedon Apr 29, 2024
After some discussion elsewhere, I think I could get behind the proposal if we change "'JSpecify-based' finding" to "JSpecify conformance finding," which I think makes clearer that this is about what the checker must be able to recognize internally in order to pass our tests. (There are surely other formulations that could work, too, but that one might minimize the edit distance :))
cpovirk commentedon May 14, 2024
Fun fact that I can't resist posting here: In one narrow way, you totally can declare a contravariant parameter type in Java:
It builds without even a warning.
("the signature of m1 is the same as the erasure (§4.6) of the signature of m2.")
cpovirk commentedon May 19, 2024
I just tried the contravariant parameter type with
ImmutableMultimap.get, since it could be nice for it to acceptObjectinstead ofK(though, if we do that, we should probably update https://errorprone.info/bugpattern/CollectionIncompatibleType accordingly :)).That turns out to not go so great: Calls that pass a
Kappear to start resolving to the supermethodMultimap.get, whose return type isCollectioninstead ofImmutableCollection, leading to build errors in code that expectsImmutableCollection.netdpb commentedon Jun 13, 2024
Proposal: As described in JSpecify Conformance: Questions and Answers, conformance tests will check that tools can recognize when a parameter's type is nullness-contravariant with respect to its supermethod, but that will impose no requirement on tools to report anything in particular to users.
Timing: This must be decided before version 1.0 of the spec.
If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.
kevinb9n commentedon Jun 14, 2024
This seems different from what Chris and I were approaching agreement on, but I am considering just agreeing to get this over with, and it probably wouldn't be a disaster. Just for now though, I am keeping this in my "probably need to create a doc to get resolution on" bucket.
cpovirk commentedon Jun 14, 2024
Is the difference just between...
...or is there anything deeper going on? Either way, we'll probably want to take it to a doc, as you said.