When initializing a val
of type Sensor
by lazy
the compiler ignores that the value returned can be null
Note: The val
is declared as Sensor
and not Sensor?
Code
private val sensorManager by lazy { getSystemService(Context.SENSOR_SERVICE) as SensorManager }
private val proximitySensor: Sensor by lazy { sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) }
Kindly note that sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY)
can also return null
Shouldn’t it raise a compile time error when assigning a nullable
to a val
which is non-null
?
When accessed from code, if proximitySensor
is null and tried to access it. It gives a runtime exception as expected.
'java.lang.String android.hardware.Sensor.getName()' on a null object reference
Also, the Android Studio gives a warning when checking for null as we have not declared it as Sensor?
if (proximitySensor == null) {
label_proximity.text = getString(R.string.error_no_sensor)
}
Using Sensor?
solves the problem but I the code should not compile without declaring a nullable type with ?