Menu

#185 A case where nullness inference doesn't quite work

open
nobody
None
5
2006-12-29
2006-12-29
Anonymous
No

If you do the following, the nullness inference fails unless you add an assertion:

?Foo bar = null;
bar = myMethod();
doStuff(bar);

Where

public Foo myMethod();
public void doStuff(Foo foo);

The compiler things that foo might be null, and so you can't call doStuff on it.

At least that's what I think is happening. Here's the sample code which this appeared in:

package kakuro;
import java.util.*;
import java.lang.ref.*;

public class CalculationTable<S, T>
{
private HashMap<S, ?SoftReference<T>> values = new HashMap();
private (S -> T) calculate;

public T get(S arg)
{
?SoftReference<T> valueRef = values.get(arg);
?T value;

if (valueRef == null)
{
value = calculate(arg);
}
else
{
value = valueRef.get();
}

if (value == null)
{
value = calculate(arg);
values.put(arg, new SoftReference(value));
}

return value;
}
}

The error occurs with the "new SoftReference(value)".

Discussion

  • Nobody/Anonymous

    Logged In: NO

    Here's a greatly pared down piece of test code:

    package test;

    public class Test1<S, T>
    {
    private (S -> T) calculate;

    public void bug(S arg)
    {
    ?T value = calculate(arg);

    T otherValue = id (value);
    Test2<T> test2 = new Test2(value : value);
    }
    }

    <T> T id (T arg) = arg;

    public class Test2<T>
    {
    T value;
    }

    I've not determined exactly how minimal this is, but it should be pretty near. Note that the nullness inference fails for both the constructor and the assignment otherValue = id (value). Also, this does appear to have something to do with the presence of the type parameters.

     
  • David R. MacIver

    Logged In: YES
    user_id=1681313
    Originator: NO

    And here's a minimal example (I thought I'd tested this example before, but apparently not):

    package nullerror;

    public void bug()
    {
    ?String value = "";
    String otherValue = value;
    }

     

Log in to post a comment.