Under Review
over 1 year ago

Strict type checking when dealing with instance attributes that might be null

When the compiler type checking is set to "Strict", errors are generated when trying to use instance attributes. For example, the following code will generate a WARNING on the "Informative" level or an "ERROR" on the "Strict" level, that says: Cannot find symbol ':format' on type 'Null'.

var latestInfo = Sensor.getInfo();
if (latestInfo != null) {
    if (latestInfo.heartRate != null) {
        var heartRateStr = latestInfo.heartRate.format("%0d");
    }
}

In this case, I would expect that the compiler can see that both the sensorInfo variable and the heartRate attribute are not null (since both case have been checked as such).

The workaround for this right now is to assign the instance variable to a local variable and then use that local variable instead. Although this is an okay solution, it is extra code and not nearly as clean. Here is the workaround code:

var latestInfo = Sensor.getInfo();
if (latestInfo != null) {
    var tmpHR = latestInfo.heartRate;
    if (tmpHR != null) {
        heartRateStr = tmpHR.format("%0d");
    }
}

This is currently happening on SDK 6.2.0