tehnolog
tehnolog

Reputation: 1214

Canvas? or Canvas in the View.onDraw() method

Android Studio generates onDraw() method in the View class like this:

override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
}

But in many samples from Google (Codelabs, courses etc) I see another version

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
}

Which version is correct? And why?

Upvotes: 1

Views: 461

Answers (1)

Sasi Kumar
Sasi Kumar

Reputation: 13288

fun onDraw(canvas: Canvas?)

This case canvas may be null. It accept null values so app may be crash null canvas object.so we have to handle nullability in all places.

onDraw(canvas: Canvas)

This case canvas must not null.so we don't care about nullability. we can avoid app crash so this is best one.

Upvotes: 1

Related Questions