why `onDraw()` method on View receives nullable canvas

Viewed 67

In a using custom views, I override onDraw(canvas:Canvas?) method many times , but I don't understand why this method get a nullable Canvas , shouldn't a view always have a canvas to draw on when it is time to draw?. I also asserted it non null and it works , but I don't want to take that risk , may be at some point it gets null. So first I want to understand in what situations that parameter can be null?

or is it just coming from java to kotlin conversion process and i can safely remove the ?from the parameter?

Thanks

1 Answers

Because the Android API was originally written in Java. And in Java, there are no non-nullable values. Since Kotlin needs to be compatible with that Java API, it needs to be a nullable parameter.

If you ever actually get a null it's a bug in the framework. I've never seen it happen. I think you're safe just letting it throw a NullPointerException if it does because you should never see it.

For the record, even the Android framework doesn't check for null on that parameter- TextView.onDraw will crash if you pass in null.

Related